java map转为json字符串
时间: 2023-11-17 10:56:08 浏览: 167
Java List或Map对象和json字符串数据的相互转化
5星 · 资源好评率100%
可以使用Jackson库将Java Map转换为JSON字符串。示例代码如下:
```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class MapToJsonExample {
public static void main(String[] args) throws JsonProcessingException {
Map<String, Object> map = new HashMap<>();
map.put("name", "John");
map.put("age", 30);
map.put("city", "New York");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(map);
System.out.println(json);
}
}
```
输出结果为:
```
{"city":"New York","name":"John","age":30}
```
阅读全文