2016-06-13 6 views
0

私は以下のようなjsonオブジェクトを持っています。2つの形式のオブジェクトを持つjsonを解析する

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

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

ここで、detailsは2つの形式で表示されます。どのようにしてRetrofit APIに使用するPOJO(Plain Old Java Object)クラスを作成できますか?

+2

ないのJavaの専門家で、私はあなたが一つのクラスに同じ名前を持つ2つのフィールドを持っていないことができますね。 1つは「詳細」で、もう1つは「詳細」でなければなりません。 –

+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を変更する必要があります。 –

関連する問題