Json Elements中的更改导致代码错误

时间:2019-04-11 00:02:49

标签: java parsing gson

我终于有了我的代码来开始解析,但是当我到达Json的某些部分时,似乎会抛出错误。由于某些原因,Json中的某些元素与名称相似的元素不同。我正在使用的API:http://api.nobelprize.org/v1/laureate.json

例如:普通元素

"year": "someYear",
 "category": "someCategory",
"share": "someint",
"motivation": "\"someMotivation\"",
"affiliations": [
                 {
                  "name": "SomeName",
                  "city": "someCity",
                  "country": "SomeCountry"
                 }
                ]

稍后在json字符串中的元素导致错误

"year": "someYear",
 "category": "someCategory",
"share": "someint",
"motivation": "\"someMotivation\"",
"affiliations": [
                  []
                ]

由于某种原因,API在关联元素中放置了一个空列表,这会导致错误。

我当前的联盟课程如下:

public class Affiliations {
    String name;
    String city;
    String country;
}

我遇到的错误:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

1 个答案:

答案 0 :(得分:0)

不幸的是JSON。您可以创建一个客户JsonDeserializer,但是它仍然必须返回某事作为会员。

class Main {
    public static void main(String[] args) {
        final String json = "{ \"name\": \"William Shakespeare\", \"affiliations\": [ { \"name\": \"Globe Theatre\" }, [] ] }";
        final Gson gson = new GsonBuilder()
                .registerTypeAdapter(Affiliation.class, new AffiliationDeserializer())
                .create();
        final Laureate laureate = gson.fromJson(json, Laureate.class);
        System.out.println(laureate);

    }

    private static class Laureate {
        String name;
        List<Affiliation> affiliations;

        public Laureate(final String name) {
            this.name = name;
        }

        public String toString() {
            return "Laureate[name=" + name + ", affiliations=" + affiliations + "]";
        }
    }

    private static class Affiliation {
        String name;

        public String toString() {
            return "Affiliation[name=" + name +"]";
        }
    }

    private static class AffiliationDeserializer implements JsonDeserializer<Affiliation> {
        // this innerGson doesn't have AffiliationDeserializer registered, 
        // so it won't get stuck in an infinite loop
        private static final Gson innerGson = new Gson();

        @Override
        public Affiliation deserialize(final JsonElement json, final Type typeOfT,
                                       final JsonDeserializationContext context)
        throws JsonParseException {
            if (json.isJsonObject()) {
                return innerGson.fromJson(json, Affiliation.class);
            } else {
                return null;
            }
        }
    }
}
Laureate[name=William Shakespeare, affiliations=[Affiliation[name=Globe Theatre], null]]

使用此方法,您的从属关系列表中包含一个空值,这很糟糕,但是朝着正确的方向迈出了一步-您可以在反序列化之后清理这些数据。