JSON Jackson 是一個Java 函式庫,它具有非常強大的資料綁定功能,並提供了一個將自訂java 物件序列化為JSON 以及將JSON 反序列化回Java 物件的框架。我們可以轉換JSON到/從 Map使用com.fasterxml.jackson.databind.ObjectMapper類別的readValue()和writeValueAsString()方法。
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 { <strong> </strong>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<strong> </strong> System.out.println(map); } }###輸出###
{"Raja":"Java Technology", "Vamsi":"Web Technology", "Ravi":"Python Technology", "Adithya":"Spark Technology"}####
以上是在Java中使用Jackson庫將JSON轉換為Map或將Map轉換為JSON?的詳細內容。更多資訊請關注PHP中文網其他相關文章!