使用 Java 中的 Jackson 库将 JSON 转换为 Map 或从 Map 转换为 JSON?
javajsonobject oriented programmingprogramming
JSON Jackson 是一个 Java 库,它具有非常强大的数据绑定功能,并提供了一个框架来将自定义 Java 对象序列化为 JSON,并将 JSON 反序列化回 Java 对象。我们可以使用 com.fasterxml.jackson.databind.ObjectMapper 类的 readValue() 和 writeValueAsString() 方法将 JSON转换为 Map 或从 Map 转换为 Map。
JSON 到 Map
语法
public <T> T readValue(String content, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException
示例
import java.io.*; import java.util.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.type.TypeReference; public class ConvertJSONToMapTest { public static void main(String args[]) { try { ObjectMapper mapper = new ObjectMapper(); String jsonString = "{\"Name\":\"Raja\", \"Technology\":\"Java\"}"; Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap = mapper.readValue(jsonString, new TypeReference<Map<String, String>>(){}); // converts JSON to Map System.out.println(jsonMap); } catch(IOException ie) { ie.printStackTrace(); } } }
输出
{Name=Raja, Technology=Java}
映射到 JSON
语法
public String writeValueAsString(Object value) throws JsonProcessingException
示例
import java.io.*; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.ObjectMapper; public class ConvertMapToJSONTest { public static void main(String args[]) throws IOException { ObjectMapper mapper = new ObjectMapper(); String jsonString = ""; Map<String, Object> map = new HashMap<String, Object>(); map.put("Raja", "Java Technology"); map.put("Ravi", "Python Technology"); map.put("Adithya", "Spark Technology"); map.put("Vamsi", "Web Technology"); jsonString = mapper.writeValueAsString(map); // converts Map to JSON System.out.println(map); } }
输出
{"Raja":"Java Technology", "Vamsi":"Web Technology", "Ravi":"Python Technology", "Adithya":"Spark Technology"}