Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an existing json string with Gson

Tags:

java

json

gson

I have a String object containing some arbitrary json. I want to wrap it inside another json object, like this:

{
   version: 1,
   content: >>arbitrary_json_string_object<<
}

How can I reliably add my json string as an attribute to it without having to build it manually (ie avoiding tedious string concatenation)?

class Wrapper {
   int version = 1;
}

gson.toJson(new Wrapper())
// Then what?

Note that the added json should not be escaped, but a be part of the wrapper as a valid json entity, like this:

{
   version: 1,
   content: ["the content", {name:"from the String"}, "object"]
}

given

String arbitraryJson = "[\"the content\", {name:\"from the String\"}, \"object\"]";
like image 663
Martin Wickman Avatar asked Dec 11 '13 15:12

Martin Wickman


1 Answers

For those venturing on this topic, consider this.

A a = getYourAInstanceHere();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(a);
jsonElement.getAsJsonObject().addProperty("url_to_user", url);
return gson.toJson(jsonElement);
like image 92
T.K. Avatar answered Oct 07 '22 08:10

T.K.