updating json object using java [closed]

此生再无相见时 提交于 2019-12-29 09:32:25

问题


Let i've an JSON Object like as shown below

{"Name":"Manu","Age":"25","Address":""}

Updation

Read the json object and need to update the address field like as given below

 {"Name":"Manu","Age":"25","Address":"XXXX"}

can anyone please tell me how to update the Address details in the JSON using java

My code

JSONObject rec = new JSONObject(data);
String name = rec.getString("Name");
String age  = rec.getString("Age"); 
String add  = rec.getString("Address"); 

now how to add some information to the address field

Update 1

String jsonstring="{Name:Manu,Age:25,Address:''}";
JSONObject object=new JSONObject(jsonstring);
JSONObject childobject=object.getJSONObject("Address");

JSONObject modifiedjson=new JSONObject();
modifiedjson.put("type",childobject.get("type"));
modifiedjson.put("value","newvalue"); 

Exception

Exception in thread "main" org.json.JSONException: JSONObject["Address"] is not a JSONObject.
    at org.json.JSONObject.getJSONObject(JSONObject.java:557)
    at kotouch.Sample.main(Sample.java:59)
Java Result: 1

回答1:


If you are using the JsonObject class it is immutable

So i believe you have to duplicate the object and change the value like this:

JSONObject object=new JSONObject(jsonstring);
JSONObject childobject=object.getJSONObject("XXXX");

JSONObject modifiedjson=new JSONObject();
modifiedjson.put("type",childobject.get("type"));
modifiedjson.put("value","newvalue");  // Add new value of XXXX here



回答2:


Parse the JSON and call the particular Key needs to be updated and set the value for the key. Please be more specific.

Create a new JSON Object

private JSONObject Data = new JSONObject;

public Test(){

try {

Data.put("address", username);
    }

catch (JSONException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();
    }
}


来源:https://stackoverflow.com/questions/19786126/updating-json-object-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!