0

I have a json file which look like as below.

 {
  "List": [
    {
      "C1": "A",
      "C2": "mail1",
      "C3": "1"
    },
    {
      "C1": "B",
      "C2": "mail2",
      "C3": "2"
    },
    {
      "C1": "C",
      "C2": "mail3",
      "C3": "3"
    },
    {
      "C1": "D",
      "C2": "mail4",
      "C3": "4"
    }
  ]
}

I wanted to add a key value to this json file.It should look like this.

  {
      "List": [
        {
          "C0": "I1",
          "C1": "A",
          "C2": "mail1",
          "C3": "1"
        },
        {
          "C0": "I2",
          "C1": "B",
          "C2": "mail2",
          "C3": "2"
        },
        {
          "C0": "I3",
          "C1": "C",
          "C2": "mail3",
          "C3": "3"
        },
        {
          "C0": "I4",
          "C1": "D",
          "C2": "mail4",
          "C3": "4"
        }
      ]
}

How can we achieve this in java8.I have tried with the jackson-all-1.9.0 jar but it is adding key value at last.Help is appriciated.

2
  • you cannot change the order in an existing map. It preserves the insertion order. One thing you can try out is by, creating a new map by putting the new key value pair and then put all the key values from the original map to the newly created map Commented Oct 13, 2017 at 9:35
  • Show us the code with which you tried to do it with jackson. It's hard to help you fix the code we can't see Commented Oct 13, 2017 at 9:35

1 Answer 1

1

You can achieve this in the following way.

try {

        JSONObject objs = new JSONObject("{\"List\":[\n" +
                "{\"C1\":\"A\",\"C2\":\"mail1\",\"C3\":\"1\"},\n" +
                "{\"C1\":\"B\",\"C2\":\"mail2\",\"C3\":\"2\"},\n" +
                "{\"C1\":\"C\",\"C2\":\"mail3\",\"C3\":\"3\"},\n" +
                "{\"C1\":\"D\",\"C2\":\"mail4\",\"C3\":\"4\"}\n" +
                "]}");

        JSONArray jsonArray=objs.getJSONArray("List");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            obj.put("C0", "I" + (i + 1));
            jsonArray.put(i,obj);
        }
        Log.v("TAG_RESULT",jsonArray.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

12 Comments

Have you compiled this code, this is not a JSONArray.
@SachinGupta Then what it is?
It is a JsonObject
Have u seen the Code properly?
Getting The JSONObject from JSONArray and then adding the key and Updating the JSONArray
|

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.