1

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.

3
  • Use a JSONParser and set the value for key2 Commented Jul 7, 2015 at 6:49
  • @UmaKanth Thanks for the reply. I don't know how to use JSONParser for array which has key value pair. Commented Jul 7, 2015 at 7:08
  • That "pattern" is JSON format. Use a JSON parser to parse it, then change the value, and use a JSON formatter to convert it back to JSON. Commented Jul 7, 2015 at 7:53

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.