2016-04-26 74 views
0

您好我使用GSON库来映射来自API的JSON响应并映射到对象。android创建一个自定义GSON反序列化来映射对象的JSON响应

这里是我的网址链接:

https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty 

我的模型类TopStory

public class TopStory implements Comparable<TopStory> { 
    int id; 
    String title; 
    String by; 
    int score; 
    List<Integer> kids; 
    long time; 
    String url; 



    public TopStory() { 
    } 

    public TopStory(int id, String title, String by, int score, long time,String url,List kids) { 
     this.id = id; 
     this.title = title; 
     this.by = by; 
     this.score = score; 
     this.time = time; 
     this.url = url; 
     this.kids = kids; 
    } 

,我创建一个函数来创建JSON响应的对象:

public static TopStory fromJson(JSONObject jsonObject) { 
     TopStory topStory = new TopStory(); 
     Gson gson = new Gson(); 
     topStory = gson.fromJson(jsonObject.toString(),TopStory.class); 

我与外地的孩子有问题。从响应这是一个JSONARRAY。我们如何反序列化并映射到对象字段List。以及我如何排除手动反序列化并分配给特定字段?任何帮助非常感谢。由于

+0

通过创建模型:http://www.jsonschema2pojo.org/ –

+0

嗨它支持deserializtion从JSON? –

+0

是的,用它来创建模型,其余的工作都是一样的。 –

回答

1

其实kidsList,它的Array如此宣布kids这样

Integer[] kids; 

happyCoding;

+0

感谢您的回复。我们应该使用int [] kids还是Integer []孩子? –

+0

使用任何东西....我更喜欢'Integer []' – Bharatesh

+0

谢谢,为我的案件工作 –

0

您可以使用Retrofit来创建api调用并创建一个可序列化的模型来获取数据。

+0

其实我使用凌空,因为它支持缓存resquest和请求优先 –

0

尝试使用

Gson gson = new GsonBuilder().create(); 
TopStory topStory = gson.fromJson(jsonObject.toString(),TopStory.class); 

List<Integer> kids; // 准确的申报

相关问题