关于java:如何直接修改JsonObject / JsonArray的值?

How to modify values of JsonObject / JsonArray directly?

一旦我已将JSON字符串解析为GSON提供的JsonObject类,(假设我不希望将其解析为任何有意义的数据对象,但严格希望使用JsonObject),那么我如何修改字段/键的值是直接的吗?

我看不到可能对我有帮助的API。

https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html


奇怪的是,答案是继续添加该属性。我一半期望使用setter方法。 :S

1
2
3
4
5
System.out.println("Before:" + obj.get("DebugLogId")); // original"02352"

obj.addProperty("DebugLogId","YYY");

System.out.println("After:" + obj.get("DebugLogId")); // now"YYY"


这用于使用JSONObject修改子键值。
导入使用的是

1
import org.json.JSONObject;

ex json :(在输入时将json文件转换为字符串)

1
2
3
4
5
6
{
   "parentkey1":"name",
   "parentkey2": {
    "childkey":"test"
    },
}

代码

1
2
3
JSONObject jObject  = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);

输出:

1
2
3
4
5
6
{
   "parentkey1":"name",
   "parentkey2": {
    "childkey":"data1"
    },
}


从Gson库的2.3版本开始,JsonArray类具有"设置"方法。

这是一个简单的例子:

1
2
3
4
5
6
7
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));

array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));

另一种方法是反序列化为java.util.Map,然后仅根据需要修改Java Map。这将Java端数据处理与数据传输机制(JSON)分开,这是我更喜欢组织代码的方式:使用JSON进行数据传输,而不是作为替换数据结构。


这实际上是文档中的全部。
JSONObject和JSONArray均可用于替换标准数据结构。
要实现设置器,只需在put(String name, Object value)之前调用remove(String name)

这是一个简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class BasicDB {

private JSONObject jData = new JSONObject;

public BasicDB(String username, String tagline) {
    try {
        jData.put("username", username);
        jData.put("tagline" , tagline);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getUsername () {
    String ret = null;
    try {
        ret = jData.getString("username");
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return ret;
}

public void setUsername (String username) {
    try {
        jData.remove("username");
        jData.put("username" , username);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getTagline () {
    String ret = null;
    try {
        ret = jData.getString("tagline");
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return ret;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
            throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
        JSONObject json = new JSONObject();
        String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
        json = new JSONObject(jsonStr);
        System.out.println(json);
        JSONArray jsonArray = json.getJSONArray("users");
        JSONArray finalJsonArray = new JSONArray();
        /**
         * Get User form setNewUser method
         */

        //finalJsonArray.put(setNewUserPreference());
        boolean has = true;
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            finalJsonArray.put(jsonObject);
            String username2 = jsonObject.getString("userName");
            if (username2.equals(username)) {
                has = true;
            }
            System.out.println("user name  are :" + username2);
            JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
            String eng = jsonObject2.getString("Eng");
            String fin = jsonObject2.getString("Fin");
            String ger = jsonObject2.getString("Ger");
            jsonObject2.put("Eng","ChangeEnglishValueCheckForLongValue");
            System.out.println(" Eng :" + eng +"  Fin" + fin +"  ger :" + ger);
        }
        System.out.println("Final JSON Array \
"
+ json);
        jsonArray.put(setNewUserPreference());
        return json;
    }