0

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.

quarks
  • 33,478
  • 73
  • 290
  • 513

1 Answers1

1

The code is strikingly similar:

String json = ...;
JsonObject jsonObj = (JsonObject) new JsonParser().parse(json);
jsonObj.addProperty("hey", "yow!");
json = jsonObj.toString();
Perception
  • 79,279
  • 19
  • 185
  • 195