【问题标题】:How to make Retrofit model with several internal lists如何使用多个内部列表制作改造模型
【发布时间】:2018-12-20 17:50:41
【问题描述】:

我想为以下 Json 创建一个模型,当我使用jsonschema2poj 网站时,返回的模型不正确并且我无权访问IdjobTitles。我为 REST API 使用改造。 请帮我制作正确的模型。

{
  "res": [
    [
      {
        "name": "tom",
        "lname": "ford",
        "Status": 3
      }
    ],
    [
      {
        "Title1": "AAA"
      },
      {
        "Title2": "BBB"
      },
      {
        "Title3": "CCC"
      }
    ],
    [
      {
        "Id": "123",
        "job": "Doctor"
      }
    ]
  ]
}

【问题讨论】:

标签: android arrays json list retrofit2


【解决方案1】:

由于您想要一个没有为数组定义键的通用机制,如果res 数组中有多个项目,您可以使用Map<String,String> 数组,然后将其包装在另一个对象中。这基本上会给出一个List<Map<String, String>>。你的班级可以是:

public class ResultObject {
    // considering that the res object has multiple
    // array of nested array of objects, if not then
    // use just Map<String, String> without the List<>

    List<Map<String, String>> mMapString;  

    public Map<String, String> getMapForIndex(int index) throws IllegalAccessException {
        if (mMapString == null || index > mMapString.size()) {
            throw new IllegalAccessException("map is null or index is too large");
        }
        return mMapString.get(index);
    }
}

你的父类是:

public class ParentObject {
    @SerializedName("res")
    @Expose
    ResultObject mResult;

    public ResultObject getResult() {
        return mResult;
    }
}

不过,如果您也可以控制后端流程,我建议使用更简洁的 JSON 结构,单独命名。

【讨论】:

  • 您可以使用 GSON 库 final MyUser user = new MyUser(); final Map&lt;String, String&gt; mMap = result.getMapForIndex(0) for (Map.Entry&lt;String, String&gt; map : mMap.entrySet()){ user.name = map.getKey("user") != null ? map.getValue() : ""; .... } 或使用 try-catch 块在 getKey("name"); 时访问它
【解决方案2】:

像这样制作 pojo 类..

public class ResItemItem{

@SerializedName("Status")
private int status;

@SerializedName("lname")
private String lname;

@SerializedName("name")
private String name;

public void setStatus(int status){
    this.status = status;
}

public int getStatus(){
    return status;
}

public void setLname(String lname){
    this.lname = lname;
}

public String getLname(){
    return lname;
}

public void setName(String name){
    this.name = name;
}

public String getName(){
    return name;
}

}

public class ResponseData{

@SerializedName("res")
private List<List<ResItemItem>> res;

public void setRes(List<List<ResItemItem>> res){
    this.res = res;
}

public List<List<ResItemItem>> getRes(){
    return res;
}

}

并将 ResponeData pojo 类传递给改造 api 响应。

我希望你知道所有关于改造的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2020-12-30
    • 1970-01-01
    • 2020-01-06
    • 2021-09-07
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多