2016-06-13 63 views
0

我有一個json對象,如下所示。解析具有兩種格式對象的json

{ 
    "products": [ 
     { 
      "details": { 
       "name": "xxx", 
       "price": "100rs" 
      }, 
      "description": "Buy this product" 

     }, { 
      "details": [{ 
       "name": "yyy", 
       "price": "200rs" 
      }], 
      "description": "another project" 
     } 
    ] 
} 

這裏的details以兩種格式呈現。我如何創建一個POJO(普通舊Java對象)類用於Retrofit api?

+2

不是Java專家,但我猜你不能有一個類中相同名稱的兩個領域。至少應該是「細節」和其他「細節」。 –

+0

使用這個在線工具,希望對你有幫助.. http://pojo.sodhanalibrary.com/ –

+0

我認爲你可以寫這樣一個自定義的反序列化器:http://stackoverflow.com/questions/35502079/custom- converter-for-retrofit-2 – nasch

回答

0

我認爲這是不好的API響應,應該從後端修復。但是如果你想解決這個問題,你必須使用String轉換器反序列化對String的響應。你不能使用Gson轉換器將它反序列化到Pojo。

StringConverter.java

public class StringConverter implements Converter { 

    @Override 
    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException { 
     String text = null; 
     try { 
      text = fromStream(typedInput.in()); 
     } catch (IOException ignored) { } 

     return text; 
    } 

    @Override 
    public TypedOutput toBody(Object o) { 
     return null; 
    } 

    public static String fromStream(InputStream in) throws IOException  { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
     StringBuilder out = new StringBuilder(); 
     String newLine = System.getProperty("line.separator"); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      out.append(line); 
      out.append(newLine); 
     } 
     return out.toString(); 
    } 
} 

API調用實現

RestAdapter restAdapter = new RestAdapter.Builder() 
      .setEndpoint(API_URL) 
      .setConverter(new StringConverter()) 
      .build(); 

YourAPI api = restAdapter.create(YourAPI.class); 
api.yourService(parameter,new RestCallback<String>() { 

    @Override 
    public void success(String response, Response retrofitResponse) { 
     super.success(response, retrofitResponse); 
     //process your response here 
     //convert it from string to your POJO, JSON Object, or JSONArray manually 

    } 

    @Override 
    public void failure(RetrofitError error) { 
     super.failure(error); 
    } 

}); 
+0

是的,看起來像api需要修改。 –