简体   繁体   English

使用Gson解析不同的JSON对象的列表

[英]Parsing a list of different JSON objects with Gson

How to parse below stream of Json objects? 如何解析下面的Json对象流? There are example for array parsing but not stream of json objects. 有数组解析的示例,但没有json对象流。 Only the first object is different other than that every other object is similar. 只有第一个对象不同,其他所有对象都相似。 Its not array but stream of json objects. 它不是数组,而是json对象流。

[{
  "code": 200,
  "request_id": "52d868df5ada23e5f289320f",
  "ok": true,
  "payload_meta": {
    "original_size": 1837,
    "size": 1837
  }
},{
  "id": "4fb56d7f273fb7ebfe22783f",
  "duration": "6:49",
  "duration_seconds": 409,
  "size_bytes": 16396948
}{
  "id": "4fb56d7f273fb7ebfe227841",
  "duration": "3:42",
  "duration_seconds": 222,
  "size_bytes": 8904980
}{
  "id": "4fb56d7f273fb7ebfe227846",
  "duration": "4:06",
  "duration_seconds": 246,
  "size_bytes": 9843339
}]

And also how to notify after parsing one object successfully instead of waiting whole stream to complete. 以及如何在成功解析一个对象后通知,而不是等待整个流完成来通知。

I made no assumptions on the kind of object you are trying to deserialize. 对于您要反序列化的对象,我没有做任何假设。 So I named Class1 and Class2 the two kind of objects and they have no relationship. 因此,我将Class1Class2命名为两种对象,它们没有关系。 I declared them as inner static classes to make compat the example, but you can move Class1 and Class2 to separate files. 我将它们声明为内部静态类以使该示例兼容,但是您可以将Class1Class2移到单独的文件中。 I paste you a ready to run code so that you can try it on your own. 我粘贴了一个准备好运行的代码,以便您可以自己尝试。

package stackoverflow.questions.q23556772;

import java.util.*;

import com.google.gson.*;

public class Q23556772 {

    public static class Class1 {
        String code;
        String request_id;
        Boolean ok;
        HashMap<String, Integer> payload_meta;

        @Override
        public String toString() {
            return "Class1 [code=" + code + ", request_id=" + request_id + ", ok=" + ok + ", payload_meta=" + payload_meta + "]";
        }

    }

    public static class Class2 {
        String id;
        String duration;
        Integer duration_seconds;
        Integer size_bytes;

        @Override
        public String toString() {
            return "Class2 [id=" + id + ", duration=" + duration + ", duration_seconds=" + duration_seconds + ", size_bytes=" + size_bytes + "]";
        }

    }


    public static void main(String[] args) {
     String json = 
             "[{                                                     "+
             "  \"code\": 200,                                       "+
             "  \"request_id\": \"52d868df5ada23e5f289320f\",        "+
             "  \"ok\": true,                                        "+
             "  \"payload_meta\": {                                  "+
             "    \"original_size\": 1837,                           "+
             "    \"size\": 1837                                     "+
             "  }                                                    "+
             "},{                                                    "+
             "  \"id\": \"4fb56d7f273fb7ebfe22783f\",                "+
             "  \"duration\": \"6:49\",                              "+
             "  \"duration_seconds\": 409,                           "+
             "  \"size_bytes\": 16396948                             "+
             "},{                                                    "+
             "  \"id\": \"4fb56d7f273fb7ebfe227841\",                "+
             "  \"duration\": \"3:42\",                              "+
             "  \"duration_seconds\": 222,                           "+
             "  \"size_bytes\": 8904980                              "+
             "},{                                                    "+
             "  \"id\": \"4fb56d7f273fb7ebfe227846\",                "+
             "  \"duration\": \"4:06\",                              "+
             "  \"duration_seconds\": 246,                           "+
             "  \"size_bytes\": 9843339                              "+
             "}]                                                     ";



     ArrayList<Object> result = new ArrayList<>();

     Gson g = new Gson();

     JsonArray e = new JsonParser().parse(json).getAsJsonArray();

     for(int i = 0; i < e.size(); i++){
         JsonObject o = e.get(i).getAsJsonObject();
         if (o.get("code") != null)
             result.add(g.fromJson(o, Class1.class));
         else if (o.get("id") != null)
             result.add(g.fromJson(o, Class2.class));
         else result.add(g.fromJson(o, Object.class));
     }

     for(Object resultObject: result)
         System.out.println(resultObject.toString());


    }

}

As you can see, I use a combination of JsonParser and Gson methods. 如您所见,我结合使用了JsonParser和Gson方法。 I use the parser to peek inside the "stream" and to decide what is the correct class to use, then I use standard Gson deserialization to do the work. 我使用解析器来查看“流”内部并确定要使用的正确类,然后使用标准Gson反序列化来完成工作。 This code could be adapted into a custom TypeAdapter , but probably it makes the code "complex" beyond your real needs. 可以将此代码改编成自定义的TypeAdapter ,但可能会使代码“复杂”,超出您的实际需求。

Final note: I edited your JSON since it was incorrect. 最后说明:我编辑了JSON,因为它不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM