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 ?

2
  • How about System.out.println(list);? Commented Jan 24, 2016 at 8:24
  • OMG! How did I miss that ? Please post it as an answer so that I can accept . Commented Jan 24, 2016 at 8:26

3 Answers 3

2

Just print it.

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

Then you can get

[{"name":"name"}, {"name":"MyName"}]
Sign up to request clarification or add additional context in comments.

Comments

0

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

new Gson().toJson(yourList, new TypeToken<List<JsonObject>>(){}.getType())

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.