【问题标题】:Json strings to Json arrayJson 字符串到 Json 数组
【发布时间】:2018-09-08 04:50:09
【问题描述】:

美好的一天!

我有一个这样的 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

但我想这不是最好的方法。有没有办法将许多 json 字符串组合到 json 数组中?我想这样做:

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

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

但是 JsonArray 给了我用 json 转义的字符串 - 像这样 -

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

我该怎么做? 谢谢。

【问题讨论】:

    标签: java json


    【解决方案1】:

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

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

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

    【讨论】:

    • 我在想它,但可能有一些 oop-way 吗? :-)。
    • 重点是你要避免不必要的从字符串到对象的映射,不是吗?
    • 也许你更喜欢这种方法:stackoverflow.com/a/22083425/3558960 但是这样做和你原来的方法基本一样。
    • @Robby Cornelissen,是的。我想你的建议会奏效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多