通过gson使用混合子对象解析json并作为列表返回 [英] Parse json with mixed child objects via gson and send back as list

查看:218
本文介绍了通过gson使用混合子对象解析json并作为列表返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



strong>示例JSON :

  {
status:OK,
结果:[
{
type:one,
Id:2170676,
count:456,
title:title,
description:description,
oneMemberOne:11,
oneMemberTwo:12,
} $
type:two,
Id:2170677,
count:123,
title:title ,
description:description,
twoMemberOne:21,
twoMemberTwo:22,
}
]

我创建了一个Parent类和两个子类:
$ b


Num :类型,ID,计数,标题,描述字段

一个扩展Num :oneMemberOne,oneMemberTwo



两个扩展Num :twoMemberOne,twoMemberTwo


现在我的问题是:
我有一个询问结果的方法。说列出< Num> getResults()




  • 我正确解析数据:

     列表< Num> result = new ArrayList< Num>(); 
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(lastResponsePayload).getAsJsonObject()
    JsonArray results = jsonObject.get(results)。getAsJsonArray();
    for(JsonElement element:results){
    JsonObject trs = element.getAsJsonObject();
    String type = trs.get(type)。getAsString();

    if(type.equals(one){
    One one = new Gson()。fromJson(element,One.class);
    result.add(product) ;
    } else if(type.equals(two){
    Two two = new Gson()。fromJson(element,Two.class);
    result.add(metaproduct);
    }
    返回结果;


  • 现在,在获得清单后,我必须这样做:

     列出< Num> results = getResults(); 
    List< One> oness = new ArrayList< One>();
    List< Two> twoss = new ArrayList< Two>();
    for(Num n:results){
    if n.type.equals(one)
    oness.add((One)n);
    else
    twoss.add((Two)n);



    $ b

    这是一个很好的设计吗?

    这个API的用户每次都必须根据父类的类型字段向下转发,因为webservice让我混合编辑孩子班的数组,我必须这样做。有没有更好的方法来解决这个问题?




    • 另一种方法是创建一个结果包含两个成员一个两个的类,并提供给我一个 List< Result> 代替 List< Num>
      ,但用户必须检查member是否是 null 或不是,然后采取适当的步骤。


    预先感谢您。

    解决方案

    我会建议你有另外一类这样的东西。它可以防止客户端代码再次旋转列表并解析出记录。

      public class结果{
    private List< One>请注意我没有运行这段代码来测试它。 oness;
    私人列表< Two> twoss;

    公共列表< One> getOness(){
    返回oness;
    }

    public void setOness(List< One> oness){
    this.oness = oness;
    }

    public List< Two> getTwoss(){
    return twoss;
    }

    public void setTwoss(List< Two> twoss){
    this.twoss = twoss;
    }
    }

    并更改



    列表< Num> getResults()




    $ b

    Result getResults( )



    如果您修改解析逻辑,用户也不必检查空值。请注意,如果我们没有结果,我们不会返回空列表,而是空列表。

     结果结果=新结果); 
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(lastResponsePayload).getAsJsonObject()
    JsonArray results = jsonObject.get(results)。getAsJsonArray();

    列表< One> oness = null;
    列表< Two> twoss = null;

    for(JsonElement element:results){
    JsonObject trs = element.getAsJsonObject();
    String type = trs.get(type)。getAsString();如果(type.equals(one)){
    if(oness == null){
    oness = new ArrayList< One>();

    if
    result.setOness(oness);
    }
    One one = new Gson()。fromJson(element,One.class);
    oness.add(product);
    } else if(type.equals(two)){
    if(twoss == null){
    twoss = new ArrayList< Two>();
    result.setTwoss(twoss);
    }
    two two = new Gson()。fromJson(element,Two.class);
    twoss.add(metaproduct);
    }
    if(oness == null){
    result.setOness(Collections。< One> EMPTY_LIST);
    }
    if(twoss == null){
    result.setTwoss(Collections。< Two> EMPTY_LIST);
    }

    返回结果;

    希望它有帮助:)


    I'm facing a problem related to parsing json which have mixed arrays of child classes, and I need to provide that as java list back to client.

    Sample JSON:

    {
      "status": "OK",
      "results": [
        {
          "type": "one",
           "Id": "2170676",
           "count": "456",
           "title": "title",
           "description": "description",
           "oneMemberOne": "11",
           "oneMemberTwo": "12",
        }
        {
          "type": "two",
          "Id": "2170677",
          "count": "123",
          "title": "title",
          "description": "description",
          "twoMemberOne": "21",
          "twoMemberTwo": "22",
        }
      ]
    }
    

    I created one Parent class and two child class from this:

    Num : type, Id, count, title, description fields

    One extends Num : oneMemberOne, oneMemberTwo

    Two extends Num : twoMemberOne, twoMemberTwo

    Now my question: I have a method for asking results. Say it List<Num> getResults()

    • I parse the data properly like this:

      List<Num> result = new ArrayList<Num>();
      JsonParser parser = new JsonParser();
      JsonObject jsonObject = parser.parse(lastResponsePayload).getAsJsonObject()
      JsonArray results = jsonObject.get("results").getAsJsonArray();
      for (JsonElement element : results) {
           JsonObject trs = element.getAsJsonObject();
           String type = trs.get("type").getAsString();
      
           if (type.equals("one") {
                One one = new Gson().fromJson(element, One.class);
                result.add(product);
           } else if (type.equals("two") {
                Two two = new Gson().fromJson(element, Two.class);
                result.add(metaproduct);
           }
      return result;
      

    • Now, on client side, after I get the list, i have to do this:

      List<Num> results = getResults();
      List<One> oness = new ArrayList<One>();
      List<Two> twoss = new ArrayList<Two>();
      for(Num n : results) {
           if(n.type.equals("one")
                oness.add((One) n);
           else
                twoss.add((Two) n);
      

    Is this a good design for this scenario ?

    User of this API has to downcast everytime based on the type field of parent class. Because webservice gives me mixed array of child classes, I have to do this. Is there any better approach to this problem ?

    • One another approach in my mind is to create a Result class which contains two members One and Two and provide my a List<Result> instead of List<Num>, but then user has to check whether member is null or not and then take appropriate steps.

    Thank you in advance.

    解决方案

    I will suggest that you have another class something like this. It prevents client code from spinning through list again and parsing out records. Please note I have not run this code to test it.

    public class Result {
        private List<One> oness;
        private List<Two> twoss;
    
        public List<One> getOness() {
            return oness;
        }
    
        public void setOness(List<One> oness) {
            this.oness = oness;
        }
    
        public List<Two> getTwoss() {
            return twoss;
        }
    
        public void setTwoss(List<Two> twoss) {
            this.twoss = twoss;
        }
    }
    

    And change

    List<Num> getResults()

    To

    Result getResults()

    also user will not have to check for nulls if you modify your parsing logic. Please see that in case we don't have results we are not returning null list but EmptyList.

    Result result = new Result();
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(lastResponsePayload).getAsJsonObject()
        JsonArray results = jsonObject.get("results").getAsJsonArray();
    
        List<One> oness = null;
        List<Two> twoss = null;
    
        for (JsonElement element : results) {
             JsonObject trs = element.getAsJsonObject();
             String type = trs.get("type").getAsString();
    
             if (type.equals("one")) {
                 if(oness == null) {
                     oness = new ArrayList<One>();
                     result.setOness(oness);
                 }
                 One one = new Gson().fromJson(element, One.class);
                 oness.add(product);
             } else if (type.equals("two")) {
                 if(twoss == null) {
                     twoss = new ArrayList<Two>();
                     result.setTwoss(twoss);
                 }
                  Two two = new Gson().fromJson(element, Two.class);
                  twoss.add(metaproduct);
             }
             if(oness == null) {
                 result.setOness(Collections.<One>EMPTY_LIST);
             }
             if(twoss == null) {
                 result.setTwoss(Collections.<Two>EMPTY_LIST);
             }
    
        return result;
    

    Hope it helps :)

    这篇关于通过gson使用混合子对象解析json并作为列表返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆