使用Java中的Jackson库将JSON与Map进行相互转换?
JSONJackson是Java库,它具有非常强大的数据绑定功能,并提供了一个框架,可将自定义Java对象序列化为JSON并将JSON反序列化为Java对象。我们可以使用com.fasterxml.jackson.databind.ObjectMapper类的readValue() 和writeValueAsString()方法将JSON 与Map 进行相互转换 。
JSON映射
语法
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"}