2017-10-14 85 views
0

如何更新json文件中的值并替换文件本身的值?我尝试了以下方法,它取代了值,但我无法在json文件中看到更新后的值。先谢谢你。将更新后的值替换为java中的嵌套json文件

final FileInputStream in = new FileInputStream(System.getProperty("user.dir") + "/" + PATH); 
     final ObjectMapper mapper = new ObjectMapper(); 
     final JsonNode tmp = mapper.readTree(in); 

    //replacing the value 
    ObjectNode.class.cast(tmp).get("url").get(0).get("path").toString().replace(DEFAULT_ENDPOINT,configuration.getApiEndPoint()); 

    //write to the file 
    byte[] contentAsByte = tmp.toString().getBytes(); 
    final FileOutputStream out = new FileOutputStream(System.getProperty("user.dir") + "/" + PATH); 
    out.write(contentAsByte); 
    out.flush(); 
    out.close(); 
    in.close();` 

回答

0

您所使用的.replace()方法是从字符串的一个,而不是从JsonNode。

使用此改变JsonNode:

// replacing the value 
    ObjectNode obj = ObjectNode.class.cast(tmp.get("url").get(0)); 
    obj.set("path", new TextNode("newValue")); 
+0

谢谢你的建议。我尝试过,但没有奏效。我可以通过添加以下内容来解决它。 ObjectNode.class.cast(tmp).get(“url”)。get(0).get(“path”))。put(DEFAULT_ENDPOINT,configuration.getApiEndPoint()); –