Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

How to modify values inside JSON object in Java

I have a JSON Object which looks like this.

{
   "result":{
      "issue_date":"20-02-2011",
      "father/husband":"Chopra",
      "name":"Variyar",
      
 "img":"/9j/4AAQSkZJRgABAQAABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKS",
      "blood_group":"",
      "dob":"11-03-1981",
      "validity":{
         "non-transport":"24-03-2010 to 23-02-2030",
         "transport":""
      },
      "cov_details":[
         {
            "issue_date":"UNIT OFFICE,TRICHY",
            "cov":"NCWG"
         }
      ],
      "dl_number":"TN0290000784",
      "address":"PERIYA COLONY  KO PAVAZHANGUDI  VIRUDHACHALAM TK"
   },
   "request_id":"a2642ae9-2f10-4e9a-9f7e-c3ee1a9a2dbe",
   "status-code":"101"
}

I want to edit the values inside of "img" which is inside "result" using java.

obj.remove("img");
obj.put("img","N/A");

But it did not work. My expected output is that the Img tag should be like this

 "img":"N/A",     

Any suggestion on how to achieve this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this. Below is both options to delete or update the data. Use com.fasterxml.jackson

  String tt = "{   "result":{      "issue_date":"20-02-2011",      "father/husband":"Chopra",      "name":"Variyar",       "img":"/9j/4AAQSkZJRgABAQAABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKS",      "blood_group":"",      "dob":"11-03-1981",      "validity":{         "non-transport":"24-03-2010 to 23-02-2030",         "transport":""      },      "cov_details":[         {            "issue_date":"UNIT OFFICE,TRICHY",            "cov":"NCWG"         }      ],      "dl_number":"TN0290000784",      "address":"PERIYA COLONY  KO PAVAZHANGUDI  VIRUDHACHALAM TK"   },   "request_id":"a2642ae9-2f10-4e9a-9f7e-c3ee1a9a2dbe",   "status-code":"101"}";
         ObjectMapper mapper = new ObjectMapper();
         mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
         JsonFactory factory = mapper.getFactory();
         JsonParser createParser = factory.createParser(tt);
         JsonNode actualObj1 = mapper.readTree(createParser);
// if you just want to update
         ((ObjectNode)((ObjectNode)actualObj1).get("result")).put("img", "n/a"); 
// if you just want delete
         ((ObjectNode)((ObjectNode)actualObj1).get("result")).remove("img");
         System.out.println(actualObj1.toString());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...