0
点赞
收藏
分享

微信扫一扫

JackSon 动态为 JSON 数据添加字段

微笑沉默 2022-12-22 阅读 88


package com.example.demo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
* @author Dongguabai
* @description
* @date 2021-03-19 10:51
*/
public class Test2222 {

public static void main(String[] args) throws JsonProcessingException {
User user = new User();
user.setName("zhangsan");
user.setAge(10);
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(user);
ObjectNode objectNode = (ObjectNode) objectMapper.readTree(jsonStr);
objectNode.put("message", 123);

String newJsonStr = objectNode.toString();
System.out.println("之前的json:" + jsonStr);
System.out.println("新的JSON:" + newJsonStr);
}
}

class User {
private String name;

private Integer age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

输出结果:

之前的json:{"name":"zhangsan","age":10}
新的JSON:{"name":"zhangsan","age":10,"message":123}

 

举报

相关推荐

0 条评论