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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I was thinking about it, but may be there is some oop-way ? :-).
The entire point is that you want to avoid unneeded mapping from string to object and back, no?
Maybe you prefer this approach: stackoverflow.com/a/22083425/3558960 But doing this is basically the same as your original approach.
@ Robby Cornelissen, yes. I guess your advice will work. Thank you.

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.