quarks
quarks

Reputation: 35282

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.

Upvotes: 0

Views: 2511

Answers (1)

Perception
Perception

Reputation: 80603

The code is strikingly similar:

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

Upvotes: 1

Related Questions