如何使用Java在现有的json文件中添加属性

时间:2019-02-18 11:22:44

标签: java

我需要在系统中已经存在的json文件中添加一个具有动态值的资源类型属性。

我尝试编写代码,但是没有用

这是我拥有的json(我只共享前几行)

{
  "id": "example",
  "text": {
    "status": "generated",

编写代码后我需要的输出是

{
  "resourceType": "Patient",
  "id": "example",
  "text": {
    "status": "generated",

添加了resourceType字段,并且我们根据要求获得了属性的值

1 个答案:

答案 0 :(得分:0)

您可以使用ObjectMapper在POJO中反序列化它,设置属性并将其反序列化为String,例如:

class Example {
    private String id;
    private String resourceType;
    private Text text;

    //getters and setters

}

class Text {

    private String status;

    //getters and setters
}

public static void main(String[] args)  throws Exception { 
    String string = "{\n" + 
            "  \"id\": \"example\",\n" + 
            "  \"text\": {\n" + 
            "    \"status\": \"generated\""
            + "} "
            + "}";
    ObjectMapper objectMapper = new ObjectMapper();
    Example example = objectMapper.readValue(string, Example.class);
    example.setResourceType("Patient");
    System.out.println(objectMapper.writeValueAsString(example));
}

Here's杰克逊的文档。