使用响应的内部JSON对象将其转换为POJO?

时间:2018-08-25 19:04:48

标签: java android json gson retrofit2

我想使用转换器从响应中立即获取POJO,但是根JSON对象不是我要反序列化为POJO的那个对象。实际上,我想将2个兄弟对象反序列化为POJO。

例如,从新的Twitch API获取流:

.map

响应将是这样的:

render()

这是我要在其中存储流数据的类:

    // Inline Render - most commonly seen example
    class MyParentView extends React.Component {

        render() {
            let json = [{
                view: 1
            }, {
                view: 2
            }, {
                view: 3
            }];

            let views = json.map((view, i) => {
                return <View key={i} parentProps={...this.props}>{view.i}</View>
            });

            return <View>{views}</View>

        }
    }

    // Outside function render
    class MyParentView extends React.Component {

        _makeViews = () => {
            let json = [{
                view: 1
            }, {
                view: 2
            }, {
                view: 3
            }];
            return json.map((view, i) => {
                return <View key={i} parentProps={...this.props}>{view.i}</View>
            });
        }

        render() {
            return <View>{this._makeViews()}</View>
        }
    }

    // Explicit render
    class MyParentView extends React.Component {

        render() {
            return <View>
                <View key={1} parentProps={...this.props}>{1}</View>
                <View key={2} parentProps={...this.props}>{2}</View>
                <View key={3} parentProps={...this.props}>{3}</View>
            </View>
        }
    }

我想将@GET("/helix/streams?first=1") Call<TwitchStream> getLatestStreamsForGame(@Query("game_id") int gameId); 的内容反序列化到上面的POJO中,并且我还需要{ "data": [ { "id": "26007494656", "user_id": "23161357", "game_id": "417752", "community_ids": [ "5181e78f-2280-42a6-873d-758e25a7c313", "848d95be-90b3-44a5-b143-6e373754c382", "fd0eab99-832a-4d7e-8cc0-04d73deb2e54" ], "type": "live", "title": "Hey Guys, It's Monday - Twitter: @Lirik", "viewer_count": 32575, "started_at": "2017-08-14T16:08:32Z", "language": "en", "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_lirik-{width}x{height}.jpg" }, ... ], "pagination": { "cursor": "eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ==" } } 中的光标。我想使用public class TwitchStream extends DataResponse{ @SerializedName("id") private String id; @SerializedName("user_id") private String userId; @SerializedName("game_id") private String gameId; @SerializedName("community_ids") private List<String> communityIds; @SerializedName("type") private String type; @SerializedName("title") private String title; @SerializedName("viewer_count") private int viewerCount; @SerializedName("started_at") private String startedAt; @SerializedName("language") private String language; @SerializedName("thumbnail_url") private String thumbnailUrl; @SerializedName("cursor") private String paginationCursor; public TwitchStream(String id, String user_id, String game_id, List<String> community_ids, String type, String title, int viewer_count, String started_at, String language, String thumbnail_url, String paginationCursor) { this.id = id; this.userId = user_id; this.gameId = game_id; this.communityIds = community_ids; this.type = type; this.title = title; this.viewerCount = viewer_count; this.startedAt = started_at; this.language = language; this.thumbnailUrl = thumbnail_url; this.paginationCursor = paginationCursor; } public String getId() { return id; } public String getUserId() { return userId; } public String getGameId() { return gameId; } public List<String> getCommunityIds() { return communityIds; } public String getType() { return type; } public String getTitle() { return title; } public int getViewerCount() { return viewerCount; } public String getStartedAt() { return startedAt; } public String getLanguage() { return language; } public String getThumbnailUrl() { return thumbnailUrl; } public String getPaginationCursor() { return paginationCursor; } } ,但是Gson想反序列化JSON根对象,并且由于它无法在此类中找到任何命名为或注释为datapagination的字段,因此它具有什么也没做。

我该怎么办? 一种解决方案是制作一个包装器类,并以这种方式创建调用:

GsonConverterFactory

但是这样我会得到一个例外:

data

另一种选择是在Gson尝试反序列化JSON根对象之前使用pagination,并且仅将@GET("/helix/streams?first=1") Call<Wrapper<TwitchStream>> getLatestStreamsForGame(@Query("game_id") int gameId); ResponseBase failed: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 10 path $.data com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 10 path $.data at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27) at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:122) at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:217) at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:116) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 10 path $.data at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:215) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)  at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39)  at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)  at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:122)  at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:217)  at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:116)  at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)  at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)  at java.lang.Thread.run(Thread.java:818) enter code here 对象传递给Gson进行反序列化。但是我该怎么办?

2 个答案:

答案 0 :(得分:1)

根据您的例外情况

  

ResponseBase失败:com.google.gson.JsonSyntaxException:   java.lang.IllegalStateException:应该为BEGIN_OBJECT,但之前为   第1行第10列的BEGIN_ARRAY路径$ .data

它等待json对象,但遇到json数组。因为在您的json结构中,“数据”是一个数组:

"data": [ // data is a json array
    {
      "id": "26007494656",
      "user_id": "23161357",
      "game_id": "417752",
      "community_ids": [
        "5181e78f-2280-42a6-873d-758e25a7c313",
        "848d95be-90b3-44a5-b143-6e373754c382",
        "fd0eab99-832a-4d7e-8cc0-04d73deb2e54"
      ],
      "type": "live",
      "title": "Hey Guys, It's Monday - Twitter: @Lirik",
      "viewer_count": 32575,
      "started_at": "2017-08-14T16:08:32Z",
      "language": "en",
      "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_lirik-{width}x{height}.jpg"
    },
    ...
  ]

因此,我建议您为包含List<Data>(数据是您当前的TwichStream类,没有分页变量)的json结构创建一个根对象,并且该根对象还包含另一个代表分页对象的类。

因此,您有3个班级,如下所示:

@Data // comes from lombok
class RootClass {
    @SerializedName("data")
    private List<Data> datas;
    private Pagination pagination;
}

@Data
class Pagination {
    private String cursor;
}

@Data
class Data {
    // your current implementation without pagination field
}

答案 1 :(得分:0)

您提供的JSON基本上需要三个类。他们是以下。

public class TwitchStream {
    public Data[] data;
    public Pagination pagination;
}

public class Pagination {
    public String cursor;
}

public class Data {
    public String id;
    public String thumbnail_url;
    public String title;
    public String game_id;
    public String started_at;
    public String[] community_ids;
    public String user_id;
    public String language;
    public String viewer_count;
    public String type;
}

希望您现在可以使用Gson轻松解析JSON响应。让我知道是否有帮助!