3

I have a case where I need to merge multiple JSONs objects into one JSON.
A single response looks like this:

{"name":"MyName"}

Multiple merged JSON looks like this:

["{\"name\":\"name\"}","{\"name\":\"MyName\"}"]

The problem here is that the child JSONs that I want to include can come either from a Java object or are available as String itself.

MyRequest request = new MyRequest();
request.setName("name");
String singleJson = new Gson().toJson(request);

String fromSomePlaceElse = "{\"name\":\"MyName\"}";;
List<String> list = Lists.newArrayList(singleJson,fromSomePlaceElse);
System.out.println(new Gson().toJson(list)); 

The above gives me the following output:

["{\"name\":\"name\"}","{\"name\":\"MyName\"}"]

instead of:

[{"name":"MyName"}, {"name":"MyName"}]

I don't want to parse the already existing JSON and do the following:

List<MyRequest> list2 = Lists.newArrayList(request, new Gson().fromJson(fromSomePlaceElse, MyRequest.class));
System.out.println(new Gson().toJson(list2));

Can this be done using Gson ?

Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33
OneMoreError
  • 7,518
  • 20
  • 73
  • 112

3 Answers3

2

Just print it.

List<String> list = Lists.newArrayList(singleJson,fromSomePlaceElse);
System.out.println(list);

Then you can get

[{"name":"name"}, {"name":"MyName"}]
0

if you want json in form of string,you can directly use ---

new Gson().toJson(yourList, new TypeToken<List<JsonObject>>(){}.getType())
Zigri2612
  • 2,279
  • 21
  • 33
0

Try the given library to merge any amount of JSON-objects at once. The result can be returned as String or JsonObject (GSON). Please reference the code in this answer.

Zon
  • 18,610
  • 7
  • 91
  • 99