Java Json字符串到Json数组

Java Json字符串到Json数组,java,json,Java,Json,你好 我有一个json对象数组,如下所示: [{ "senderDeviceId":0, "recipientDeviceId":0, "gmtTimestamp":0, "type":0 }, { "senderDeviceId":0, "recipientDeviceId":0, "gmtTimestamp":0, "type":4 }] 出于某些原因,我需要拆分到每个元素并保存到存储器。最后我有很多像这样的东西 { "senderDevi

你好

我有一个json对象数组,如下所示:

[{
   "senderDeviceId":0,
   "recipientDeviceId":0,
   "gmtTimestamp":0,
   "type":0
 }, 
 {
  "senderDeviceId":0,
  "recipientDeviceId":0,
  "gmtTimestamp":0,
   "type":4
 }]
出于某些原因,我需要拆分到每个元素并保存到存储器。最后我有很多像这样的东西

{ "senderDeviceId":0,
  "recipientDeviceId":0,
  "gmtTimestamp":0,
  "type":0
}
{
  "senderDeviceId":0,
  "recipientDeviceId":0,
  "gmtTimestamp":0,
  "type":4
} 
过了一段时间,我需要将其中的一些组合回到json数组中。 如我所见,我可以从存储器中获取对象,使用Gson将它们转换为对象,将对象输出到列表中,如下所示:

 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
但是JsonArray给了我带json的转义字符串-就像这样-

["{
     \"senderDeviceId\":0,
     \"recipientDeviceId\":0,
     \"gmtTimestamp\":0,
     \"type\":4
 }"," 
 {
     \"senderDeviceId\":0,  
     \"recipientDeviceId\":0,  
     \"gmtTimestamp\":0,  
     \"type\":0  
  }"]
我该怎么做?
谢谢。

冒着让事情变得太简单的风险:

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

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

为您节省了一个反序列化/序列化周期。

我正在考虑,但可能有一些oop方法?:-)。关键是你想避免不必要的从字符串到对象再到对象的映射,不是吗?也许你更喜欢这种方法:但这样做基本上和你原来的方法一样。@Robby Cornelissen,是的。我想你的建议会管用的。非常感谢。
String first = "..."; 
String second = "...";

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