2015-02-24 43 views
0

我收到此JSON字符串:Retrofit - 如何用不同類型的元素分析數組?

{ 
    "response": [ 
    346, 
    { 
     "id": 564, 
     "from_id": -34454802, 
     "to_id": -34454802, 
     "date": 1337658196, 
     "post_type": "post" 
    }, 
    { 
     "id": 2183, 
     "from_id": -34454802, 
     "to_id": -34454802, 
     "date": 1423916628, 
     "post_type": "post" 
    }, 
    { 
     "id": 2181, 
     "from_id": -34454802, 
     "to_id": -34454802, 
     "date": 1423724270, 
     "post_type": "post" 
    }] 
} 

創建以下類:

public class Response { 
    @SerializedName("response") 
    ArrayList<Post> posts; 
} 

public class Post { 
    int id; 
    int from_id; 
    int to_id; 
    long date; 
    String post_type; 
} 

當我嘗試解析響應,我得到錯誤:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 19 path $.response[0] 

這是因爲數組的第一個元素是數字。需要哪種模型才能正常運行?

+3

您的'JSON'響應字符串無效。你可以在這裏查看http://json.parser.online.fr/ – 2015-02-24 12:36:25

+0

對不起,我編輯帖子 – 2015-02-24 12:46:02

+0

你如何期待346號碼被翻譯成「Post」類型的對象? – splinter123 2015-02-24 13:05:36

回答

1

改裝不起作用機智直接使用Converter默認GsonConverter可用。這就是爲什麼需要自定義Converter實現。

此帖子using-gson-to-parse-array-with-multiple-types應該有助於實施。

要設置轉換器只需使用:

RestAdapter getRestAdapter(...) { 
    return new RestAdapter.Builder() 
      ... 
      .setConverter(converter) 
      ... 
      .build(); 
} 
+0

謝謝,它的工作原理! – 2015-03-25 11:00:46

1

模型類應該是這樣的,模型對象始終應該是這樣的字符串或用ArrayList的類對象或字符串Object.If你提到int,你會得到非法狀態例外。

public class Pojo 
{ 
    private Response[] response; 

    public Response[] getResponse() 
    { 
     return response; 
    } 

    public void setResponse (Response[] response) 
    { 
     this.response = response; 
    } 
} 


public class Response 
{ 
    private String id; 

    private String to_id; 

    private String from_id; 

    private String post_type; 

    private String date; 

    public String getId() 
    { 
     return id; 
    } 

    public void setId (String id) 
    { 
     this.id = id; 
    } 

    public String getTo_id() 
    { 
     return to_id; 
    } 

    public void setTo_id (String to_id) 
    { 
     this.to_id = to_id; 
    } 

    public String getFrom_id() 
    { 
     return from_id; 
    } 

    public void setFrom_id (String from_id) 
    { 
     this.from_id = from_id; 
    } 

    public String getPost_type() 
    { 
     return post_type; 
    } 

    public void setPost_type (String post_type) 
    { 
     this.post_type = post_type; 
    } 

    public String getDate() 
    { 
     return date; 
    } 

    public void setDate (String date) 
    { 
     this.date = date; 
    } 
} 
相關問題