user1734980
user1734980

Reputation: 45

Add a key value in json file using java

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.

Upvotes: 0

Views: 693

Answers (1)

Chandan kushwaha
Chandan kushwaha

Reputation: 949

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

Upvotes: 1

Related Questions