使用java更新json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19786126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:12:24  来源:igfitidea点击:

updating json object using java

javaupdatesjsonobject

提问by

Let i've an JSONObject like as shown below

让我有一个JSON如下所示的对象

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

Updation

更新

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

读取 json 对象并需要更新地址字段,如下所示

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

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

谁能告诉我如何更新的详细地址JSON使用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

更新 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

回答by Nasruddin

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

解析 JSON 并调用需要更新的特定 Key 并设置该键的值。请更具体。

Create a new JSON Object

创建一个新的 JSON 对象

private JSONObject Data = new JSONObject;

public Test(){

try {

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

catch (JSONException e) {

  // TODO Auto-generated catch block

  e.printStackTrace();
    }
}

回答by Rawa

If you are using the JsonObject classit is immutable

如果您使用的是JsonObject 类,它是不可变的

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