2015-02-24 40 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; 
    } 
} 
相关问题