How to convert a map to a JSON string in Java?
To convert a Map to a JSON string, you can use JSON libraries such as Jackson or Fastjson. Below is an example code using the Jackson library:
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) {
// 创建一个Map对象
Map<String, Object> map = new HashMap<>();
map.put("name", "John");
map.put("age", 30);
map.put("city", "New York");
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
try {
// 将Map对象转换为JSON字符串
String json = mapper.writeValueAsString(map);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
The output is:
{"name":"John","age":30,"city":"New York"}
Before using the Jackson library, it is necessary to import the relevant dependencies. If using Maven, you can add the following dependencies in the pom.xml file.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>