2016-09-07 16 views
0

我想要使用retrofit2和GSON來使用JSON。如何在Retrofit2中準備JSON結果(在發送到GsonConverterFactory之前)

以下是服務器提供的響應。請注意,「d」的值是有效JSON的字符串(一旦刪除斜槓)。

{ 「d」: [{\」 號碼\ 「:\」 2121 \ 「\ 」NumberOfAppearances \「:2,\ 」獎品\「:
[{\」 DrawDate \ 「:\」\/Date(1439654400000)\/\「,\」PrizeCode \「:\」S \「}, {\」DrawDate \「:\」\/Date(874771200000)\/\「 「PrizeCode \」:\ 「S \」}]}] }

是否有使用retrofit2在通話過程中preparse的json的,以retrofitService得到d的值內的對象的方式?

Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      //is there anything i can do here to do preparsing of the results? 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

IQueryLocations = retrofit.create(IMyQuery.class); 

//currently GsonResults is the string value of d, instead of the JSON objects 
Call<GsonResult> result = IMyQuery.doQuery("2121"); 

理想情況下,我想插入addConverterFactory前一個方法調用做preparsing

的preparsing方法的輸出會像下面的一些事情:

{「d」 :[{「Number」:「2121」,「NumberOfAppearances」:2,「獎品」:
[{「DrawDate」:1439654400000,「PrizeCode」:「S」}, {「DrawDate」:874771200000,「PrizeCode 「:」S「}]}]}

+1

這是不可能preparse的響應,你沒有在開始的反應。因此,最簡單的方法是從改造中獲得原始響應,然後根據您的需要進行解析。 –

回答

1

這不是你理想的解決方案,但你可以返回一個包裝的結果數據:

class WrappedGsonResult { 
    private static final Gson GSON = new Gson(); 

    @SerializedName("d") 
    private String data; 

    GsonResult() {} 

    public GsonResult getData() { 
     return GSON.fromJson(this.data, GsonResult.class); 
    } 
} 

然後:

Call<WrappedGsonResult> result = IMyQuery.doQuery("2121"); 
result.enqueue(new Callback() { 
    @Override 
    public void onResponse(final Call<WrappedGsonResult> call, final Response<WrappedGsonResult> response) { 
     if (response.isSuccessful()) { 
      GsonResult result = response.body().getData(); 
      // ... 
     } else { 
      // ... 
     } 
    } 

    // ... 
}); 
0

要排除雙引號,您需要使用GsonBuilder提供的excludeFieldsWithoutExposeAnnotation()

例如:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 

Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      // Add Gson object 
      .addConverterFactory(GsonConverterFactory.create(gson)) 
      .build(); 

希望這有助於。

+1

'excludeFieldsWithoutExposeAnnotation' does:'配置Gson以排除所有字段不考慮序列化或反序列化,而沒有與引用無關的Expose註釋「'。 –

相關問題