Retrofit2和Gson如何解析不一致的字段

时间:2019-04-04 10:44:48

标签: gson retrofit2

我有一个类似于下面的课程Setiment:

@Data
@NoArgsConstructor
public class Sentiment {

    /**
     * sentiment : 0.20365833333333336
     * totalScores : 24
     * positive : 0.88
     * negative : 0.12
     */

    public Double sentiment;
    public Double totalScores;
    public Double positive;
    public Double negative;

}

我使用Retrofit2解析响应:

{sentiment:{content.....}}

但是当情绪为空时,服务器将响应:

{sentiment:[]}

我不知道如何解析并尝试修改gson TypeAdapter:

public class SentimentTypeAdapter extends TypeAdapter<Sentiment> {
    @Override
    public void write(JsonWriter out, Sentiment value) throws IOException {
        out.beginObject();
        out.name("sentiment").value(value.sentiment);
        out.name("totalScores").value(value.totalScores);
        out.name("positive").value(value.positive);
        out.name("negative").value(value.negative);
        out.endObject();
    }

    @Override
    public Sentiment read(JsonReader in) throws IOException {
        Sentiment sentiment = new Sentiment();
        try {
            in.beginArray();
        } catch (Exception e) {
            in.endArray();
            in.beginObject();
            while (in.hasNext()) {
                switch (in.nextName()) {
                    case "sentiment":
                        sentiment.sentiment = in.nextDouble();
                        break;
                    case "totalScores":
                        sentiment.totalScores = in.nextDouble();
                        break;
                    case "positive":
                        sentiment.positive = in.nextDouble();
                        break;
                    case "negative":
                        sentiment.negative = in.nextDouble();
                        break;
                }
            }
            in.endObject();
        }
        return sentiment;
    }
}

gson和改造:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Sentiment.class, new SentimentTypeAdapter())
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(host)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okHttpClient)

但是出错,提示:

Expected END_OBJECT but was END_ARRAY at line 1 column 4298 path $..sentiment[0]"

我想知道JsonReader(in)如何在in.beginArray或in.beginObject之前知道它JsonObject或JsonArray,以及如何正确解析它?

0 个答案:

没有答案