ObjectMapper 類別提供了在 Java 物件和匹配 JSON 結構之間轉換的功能。我們可以使用tree-like 資料結構來實現將Object Model 表示的JSON 資料映射到特定的Java 對象,該資料結構讀取記憶體中的整個JSON 內容並將其存儲。第一步,將 JSON 資料讀入 JsonNode object ,然後透過呼叫 ObjectMapper # 的 treeToValue() 方法將其對應到另一個實例##class.
語法public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException
import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; public class JsonTreeModelDemo { public static void main(String[] args) throws JsonProcessingException, IOException { String jsonString = "{\"id\":\"102\", \"name\":\"Raja Ramesh\", \"address\":[{\"area\":\"Madhapur\", \"city\":\"Hyderabad\"}]}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); User user = objectMapper.treeToValue(jsonNode, User.class); System.out.println(user); } } // User class class User { private int id; private String name; private Address[] address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address[] getAddress() { return address; } public void setAddress(Address[] address) { this.address = address; } <strong> @Override </strong> public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append(id).append(","); sb.append(name).append(","); for(Address address1 : address) { sb.append(address1).append(","); } sb.append("}"); return sb.toString(); } } // Address class class Address { private String area; private String city; public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } <strong> </strong> @Override<strong> </strong> public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append(area).append(","); sb.append(city); sb.append("}"); return sb.toString(); } }
{102,Raja Ramesh,{Madhapur,Hyderabad},}
以上是如何在Java中使用Jackson物件模型來映射JSON資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!