Search code examples
javajsongsonjson-simple

Insert node in a JSON String


Using Google Gson library how can I inject a element in the root node of a JSON string?

With JSON.Simple it very easy:

        String json = ...
        JSONObject jsonObj = (JSONObject) JSONValue.parse(json);
        jsonObj.put("hey", "yow!"); 
        json = jsonObj.toJSONString(); // Now we have injected a node element

I've been figuring out how can do this with Gson. You might ask why I need Gson when I can do this with JSON.Simple library; the answer is that, there's a handy object serialization/deserialization function that the library have.


Solution

  • The code is strikingly similar:

    String json = ...;
    JsonObject jsonObj = (JsonObject) new JsonParser().parse(json);
    jsonObj.addProperty("hey", "yow!");
    json = jsonObj.toString();