如何在Java中使用Jackson对象模型映射JSON数据?

2023年 9月 1日 130.9k 0

如何在Java中使用Jackson对象模型映射JSON数据?

The ObjectMapper class provides functionality for converting between Java objects and matching JSON constructs. We can achieve mapping of JSON data represented by an Object Model to a particular Java object using a tree-like data structure that reads and stores the entire JSON content in memory. In the first step, read the JSON data into the JsonNode object then mapped it to another instance by calling the treeToValue() method of ObjectMapper class.

Syntax

public T treeToValue(TreeNode n, Class valueType) throws JsonProcessingException

登录后复制

Example

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;
}
@Override
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;
}
@Override
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数据?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论