1

Good day!

I have an array of json objects like this :

[{
   "senderDeviceId":0,
   "recipientDeviceId":0,
   "gmtTimestamp":0,
   "type":0
 }, 
 {
  "senderDeviceId":0,
  "recipientDeviceId":0,
  "gmtTimestamp":0,
   "type":4
 }]

For some reasons I need to split then to each element and save to storage. In the end I have many objects like

{ "senderDeviceId":0,
  "recipientDeviceId":0,
  "gmtTimestamp":0,
  "type":0
}
{
  "senderDeviceId":0,
  "recipientDeviceId":0,
  "gmtTimestamp":0,
  "type":4
} 

After some time I need to combine some of them back into json array. As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:

 String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
 String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}

 BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
 BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);

 List<BaseMessage> bmlist = new ArrayList<>();
 bmlist.add(msg1);
 bmlist.add(msg2);
 //and then Serialize to json

But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:

JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);

JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);

But JsonArray gives me escaped string with json - like this -

["{
     \"senderDeviceId\":0,
     \"recipientDeviceId\":0,
     \"gmtTimestamp\":0,
     \"type\":4
 }"," 
 {
     \"senderDeviceId\":0,  
     \"recipientDeviceId\":0,  
     \"gmtTimestamp\":0,  
     \"type\":0  
  }"]

How can I do this? Thank you.

Jay Dangar
  • 3,271
  • 1
  • 16
  • 35
RedCollarPanda
  • 1,389
  • 1
  • 20
  • 40

1 Answers1

1

At the risk of making things too simple:

String first = "..."; 
String second = "...";

String result = "[" + String.join(",", first, second) + "]";

Saves you a deserialization/serialization cycle.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156