Search code examples
javajsonsimplejsonjsonparser

Java Simple json not replacing the value of a attribute


As the tital states above I am trying to replace the value for "name" to "abc" but that does not seem to overwrite it as it's the same value after replacing it using the Simple Json java code.

This is my java code:

    String jsonString = 
    "{"
        + "\"data\":"
        + "["
            + "{"
                + "\"jazz\":\"black\","
                + "\"name\":\"white\","
                + "\"given\":\"red\","
                + "\"sam\":\"blue\","
                + "\"mail\":\"yellow\","
                + "\"member\":\"green\","
                + "\"department\":\"green\","
                + "\"title\":\"green\""
            + "}"
        + "]"
    + "}";
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
    JSONObject newJSON = new JSONObject();

    jsonObj.remove("name");
    jsonObj.put("name", "abc");

As I said, the code above seems to not do anything for the "name" attribute that's already in the json structure. The output for the above looks like this:

{
    "data": [
        {
            "given": "red",
            "mail": "yellow",
            "jazz": "black",
            "name": "white",
            "member": "green",
            "department": "green",
            "title": "green",
            "sam": "blue"
        }
    ],
    "name": "abc"
}

What the output should look like:

{
    "data": [
        {
            "given": "red",
            "mail": "yellow",
            "jazz": "black",
            "name": "abc",
            "member": "green",
            "department": "green",
            "title": "green",
            "sam": "blue"
        }
    ]
}

Any idea as to why its not changing it?

UPDATE 1

enter image description here


Solution

  • this worked for me:

    JSONArray jsonArray = (JSONArray)jsonObj.get("data");
        JSONObject jsonObject = ((JSONObject)(jsonArray).get(0));
        jsonObject.put("name", "abc");
        System.out.println(jsonObj.toJSONString());