Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3);使用Java语言将上面这个map转为JSON
时间: 2024-05-01 14:16:40 浏览: 103
json转map对象方法.java
5星 · 资源好评率100%
使用Jackson库可以将Java对象转为JSON格式,示例代码如下:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(map);
System.out.println(json);
}
}
```
输出结果为:
```
{"orange":3,"banana":2,"apple":1}
```
阅读全文