prashanth
prashanth

Reputation: 85

Update value in Array which has pattern in Java

I have an array which has pattern [{"key1":"value1","key2":"value2"}].

I want to update value2 in the above array.

Please suggest how to proceed using Java.

Thanks in Advance.

Upvotes: 1

Views: 294

Answers (2)

cнŝdk
cнŝdk

Reputation: 32175

You can use JSONArray and JSONObject to parse your json array from your string, and change the value of value2 using its key key2:

JsonArray jsonArray = JsonArray.readFrom("[{\"key1\":\"value1\",\"key2\":\"value2\"}]");
for(int i=0; i<jsonArray.length();i++){
   JSONObject jo=jsonArray.get(i);
   if(jo.has("key2")) {
      jo.remove("key2");
      jo.put("key2", "new value");
   }
}

And finally change it back to String json:

String changedJSON = jsonArray.toString();

Upvotes: 1

Garry
Garry

Reputation: 4543

You can try like this:

JSONObject object = new JSONObject("[{"key1":"value1","key2":"value2"}]");

String[] keys = JSONObject.getNames(object);

for (String key : keys)
{
    if(key.equals("key2")){
       object.put(key, "new value");
    }
}

Upvotes: 0

Related Questions