代码之家  ›  专栏  ›  技术社区  ›  Learning

Java用字符串值替换JsonNode

  •  0
  • Learning  · 技术社区  · 7 年前

    我是一个Java的noob,正在努力处理类型转换。我有一个JSON对象,如下所示:

       [  
           {  
            "A":{  
               "B":{  
                  "C":"Message",
                  "D":"FN1"
               }
            }
           }
        ] 
    

    我想把它转换成:

      [  
           {  
            "A":{  
               "B": "My String Message"
            }
           }
        ]
    

       JsonNode newNode = new TextNode("My String Message");
       ObjectNode nodeObj = (ObjectNode) jsonNode;
       nodeObj.removeAll();
       nodeObj.set(newNode);
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   CryptoFool Sachithra Dilshan    7 年前

    你的代码有点小问题。添加新文本条目时,必须提供要与新文本节点关联的键值。所以这一行:

    nodeObj.set(newNode);
    

    只需要这样:

    nodeObj.set("B", newNode);
    

    下面是一个完整的示例,它与您在问题中所展示的完全相同,结合了您提供的代码,只做了以下一个小修复:

    public static void main(String... args) throws IOException {
    
        // Read in the structure provided from a text file
        FileReader f = new FileReader("/tmp/foox.json");
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(f);
    
        // Print the starting structure
        System.out.println(rootNode);
    
        // Get the node we want to operate on
        ObjectNode jsonNode = (ObjectNode)rootNode.get(0).get("A");
    
        // The OPs code, with just the small change of adding the key value when adding the new String
        JsonNode newNode = new TextNode("My String Message");
        ObjectNode nodeObj = (ObjectNode) jsonNode;
        nodeObj.removeAll();
        nodeObj.set("B", newNode);
    
        // Print the resulting structure
        System.out.println(rootNode);
    }
    

    结果是:

    [{"A":{"B":{"C":"Message","D":"FN1"}}}]
    [{"A":{"B":"My String Message"}}]