Reputation: 13329
Lets say I gave a JSONObject
{
"person":{"name":"Sam", "surname":"ngonma"},
"car":{"make":"toyota", "model":"yaris"}
}
How do I update some of the values in the JSONObject?
Like below :
String name = jsonArray.getJSONObject(0).getJSONObject("person").getString("name");
name = "Sammie";
Upvotes: 78
Views: 309581
Reputation: 47
JSONObject objectJson = new JSONObject(gson().toJson(verbaDetalhe));
objectJson.put("Verba", verbaEditada);
My solution was edited via put the value of the key field.
Upvotes: 0
Reputation: 13509
I created my own Method which replaces a JSON value (using org.json.JSONObject) with a particular value.
public static String replaceJSONValueAtPath(String jsonString, String[] pathToValue, Object value) throws JSONException {
JSONObject obj = new org.json.JSONObject(new JSONTokener(jsonString));
JSONObject current = obj;
// Traverse the JSON tree along the path specified
for (int i = 0; i < pathToValue.length - 1; i++) {
current = current.getJSONObject(pathToValue[i]);
}
// Replace the value at the specified path
current.put(pathToValue[pathToValue.length - 1], value);
return obj.toString();
}
Here is the test :
@Test
public void test() throws JSONException {
String stringIn = "{'a': {'b' : {'c': 'oldValue'} }}";
String stringOut = TestUtils.replaceJSONValueAtPath(stringIn, new String[]{"a", "b", "c"}, "newValue");
String sTest = "{\"a\":{\"b\":{\"c\":\"newValue\"}}}";
Assertions.assertEquals(sTest, stringOut);
}
Upvotes: 0
Reputation: 51
String jsonDataString = "{\n" +
" \"Name\": \"Hello World\",\n" +
" \"Description\": \"sent\",\n" +
" \"Roles\": [\n" +
" {\n" +
" \"Profile\": \"rolec\"\n" +
" },\n" +
" {\n" +
" \"Profile\": \"rolec\"\n" +
" },\n" +
" {\n" +
" \"Profile\": \"rolec\"\n" +
" }\n" +
" ]\n" +
"}";
DocumentContext json = JsonPath.parse(jsonDataString);
String jsonPath = "$.Name";
String newValue = "SYED";
DocumentContext finaljson = json.set(jsonPath, newValue);
System.out.println(finaljson.jsonString());
Upvotes: 0
Reputation: 467
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.addProperty("name", "Sammie");
Use addProperty()
with overloads. If the property exists, will update the value. If it does not, will add it as a new one.
Upvotes: 0
Reputation: 29
Recursive way to update value in depth in Kotlin
Example: setJsonValue("obj1/obj2/keyToUpdate", "new value")
fun setJsonValue(path: String, value: Any?) {
setJsonValueRec(
path = path.split("/"),
index = 0,
obj = jsonObj,
value = value
)
}
private fun setJsonValueRec(path: List<String>, index: Int, obj: JSONObject, value: Any?): JSONObject {
return obj.put(
path[index],
when (index) {
path.lastIndex -> value
else -> setJsonValueRec(
path = path,
index = index + 1,
obj = obj.getJSONObject(path[index]),
value = value
)
}
)
}
Upvotes: 0
Reputation: 29
Generic way to update the any JSONObjet with new values.
private static void updateJsonValues(JsonObject jsonObj) {
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
JsonElement element = entry.getValue();
if (element.isJsonArray()) {
parseJsonArray(element.getAsJsonArray());
} else if (element.isJsonObject()) {
updateJsonValues(element.getAsJsonObject());
} else if (element.isJsonPrimitive()) {
jsonObj.addProperty(entry.getKey(), "<provide new value>");
}
}
}
private static void parseJsonArray(JsonArray asJsonArray) {
for (int index = 0; index < asJsonArray.size(); index++) {
JsonElement element = asJsonArray.get(index);
if (element.isJsonArray()) {
parseJsonArray(element.getAsJsonArray());
} else if (element.isJsonObject()) {
updateJsonValues(element.getAsJsonObject());
}
}
}
Upvotes: 1
Reputation: 721
Hello I can suggest you universal method. use recursion.
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<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
It should work. If you have questions, go ahead.. I'm ready.
Upvotes: 6
Reputation: 13
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;
}
Upvotes: 0
Reputation: 24334
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
Upvotes: 133
Reputation: 10677
Remove key and then add again the modified key, value pair as shown below :
JSONObject js = new JSONObject();
js.put("name", "rai");
js.remove("name");
js.put("name", "abc");
I haven't used your example; but conceptually its same.
Upvotes: 38