开发者

Android - Handling incorrect data returned from API - JSON deserialization using GSON

开发者 https://www.devze.com 2023-04-12 04:25 出处:网络
I\'m having a problem with some JSON being returned back from an API where the data is not in an expected format.The documentation for the API states that the element \"ShowEpisodes\" is an Array[], w

I'm having a problem with some JSON being returned back from an API where the data is not in an expected format. The documentation for the API states that the element "ShowEpisodes" is an Array[], which is the case in the 2nd element below. But as you can see in the first instance, if the "ShowEpisodes" element doesn't contain any items, it comes back as an empty string.

Is there some way that I can handle this issue? I've contacted the API's support staff to find out why this is returning an empty string, but have yet to hear back and in the meantime I'm trying to find a workaround.

Simplified JSON from API:

ShowSeasons: [
    {
        ShowEpisodes: ""
    },
    {
        ShowEpisodes: { … }
    }
]

Class Objects:

public static class ShowSeason implements Serializable {
    private static final long serialVersionUID = 1L;

    public ShowEpisodeInfo ShowEpisodes;
}

public static class ShowEpisodeInfo implements Seri开发者_如何转开发alizable {
    private static final long serialVersionUID = 2L;

    public List<SeasonProgramDetails> Program;
}

Stack Trace:

com.google.gson.JsonParseException: Expecting object found: ""
    at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:99)
    at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:158)
    at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:131)
    at com.google.gson.JsonDeserializationVisitor.visitChild(JsonDeserializationVisitor.java:107)
    at com.google.gson.JsonDeserializationVisitor.visitChildAsObject(JsonDeserializationVisitor.java:95)
    at com.google.gson.JsonObjectDeserializationVisitor.visitObjectField(JsonObjectDeserializationVisitor.java:61)
    at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:164)
    at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:131)
    ........

Does anybody know of a way to handle both an empty string and an array of an object for when the API returns bad data? Or possibly a way to suppress the exception so that I just drop the bad data

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号