参考文档:https://github.com/FasterXML/jackson-databind
关于ObjectMapper的线程安全
截自官方文档:
组合多个对象的属性构成JSON(以及添加自定义属性)
Code:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class TestJackson { private static final ObjectMapper MAPPER = new ObjectMapper(); public static void main(String[] args) { Foo foo = new Foo("value1", "value2"); Bar bar = new Bar("value3", "value4"); ObjectNode root = MAPPER.valueToTree(foo); ObjectNode node = MAPPER.valueToTree(bar); root.setAll(node); root.put("extraFiled", "value5"); String jsonString = null; try { jsonString = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(root); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println(jsonString); } }
Output:
PS. 单词打错:filed => field