java-更新JSONObj中的元素
可以说我给了一个JSONObject
{
"person":{"name":"Sam", "surname":"ngonma"},
"car":{"make":"toyota", "model":"yaris"}
}
如何更新JSONObject中的某些值?
像下面这样:
String name = jsonArray.getJSONObject(0).getJSONObject("person").getString("name");
name = "Sammie";
Harry asked 2020-02-10T13:55:32Z
4个解决方案
101 votes
使用put方法:[https://developer.android.com/reference/org/json/JSONObject.html]
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
cowls answered 2020-02-10T13:55:49Z
25 votes
删除键,然后再次添加修改后的键,值对,如下所示:
JSONObject js = new JSONObject();
js.put("name", "rai");
js.remove("name");
js.put("name", "abc");
我没有用你的榜样。 但在概念上是相同的
rai.skumar answered 2020-02-10T13:56:14Z
5 votes
您好,我可以建议您使用通用方法。 使用递归。
public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
JSONObject json = new JSONObject()
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
它应该工作。 如果您有任何疑问,请继续..我准备好了。
eabyshev answered 2020-02-10T13:56:39Z
-1 votes
public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
JSONObject json = new JSONObject();
// get the keys of json object
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(obj.getJSONObject(key), keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(jArray.getJSONObject(i), keyString, newValue);
}
}
}
return obj;
}
shafi kk answered 2020-02-10T13:56:54Z