改造:如何决定班级成员?

时间:2017-01-28 23:22:16

标签: java android gson models retrofit2

我一直在尝试为Android改造。响应为空。如果我的理解是正确的,这可能是因为我的模型类中的响应400响应或响应建模不正确。我得到的回应如下:

{"itemA":"data",
"itemB":"data",
"itemC":"data",
"ItemC":"",
"result_arr":[{"Val1":"A","Val2":"","id":"id","pr":"$0.00","sid":"a","cid":"a","price":"$0.00","cool_down":"0%","url":"","name":"Name"},
{"Val1":"A","Val2":"","id":"id","pr":"$0.00","sid":"a","cid":"a","price":"$0.00","cool_down":"0%","url":"","name":"Name"}]
,"statusCode":"200"}

我定义的模型如下:

API结果

public class APIResultModel {
@SerializedName("itemA")
public String itemA;
@SerializedName("itemB")
public String itemB;
@SerializedName("itemC")
public String itemC;
@SerializedName("itemD")
public string itemD;
@SerializedName("results_arr")
public List<ProductModel> results_arr;
@SerializedName("status_code")
public String statusCode;
}

结果数组模型:

public class ResultArrayModel {
public String val1;
public String val2;
public String id;
public String pr;
public String sid;
public String cid;
public String price;
public String cool_down;
public String url;
public String name;
}

此响应的模型应该如何?模型如何从响应值中得出?

2 个答案:

答案 0 :(得分:2)

查看您的代码,您似乎正在使用Gson

要让Gson创建pojo,您的模型serializedNames必须与您获得的json响应相匹配。

你必须改变:

@SerializedName("status_code")

为:

@SerializedName("statusCode")

确保所有属性都符合此规则,您就可以了。

答案 1 :(得分:0)

鉴于JSON:

{
    "itemA": "data",
    "itemB": "data",
    "itemC": "data",
    "ItemD": "",
    "result_arr": [
        {
            "Val1": "A",
            "Val2": "",
            "id": "id",
            "pr": "$0.00",
            "sid": "a",
            "cid": "a",
            "price": "$0.00",
            "cool_down": "0%",
            "url": "",
            "name": "Name"
        },
        {
            "Val1": "A",
            "Val2": "",
            "id": "id",
            "pr": "$0.00",
            "sid": "a",
            "cid": "a",
            "price": "$0.00",
            "cool_down": "0%",
            "url": "",
            "name": "Name"
        }
    ],
    "statusCode": "200"
}

您的api结果模型可能是:

public class APIResult {

    public String itemA;

    public String itemB;

    public String itemC;

    public String itemD;

    @SerializedName("results_arr")
    public List<Product> products;

    public String statusCode;
}

您的产品型号可能是:

public class Product {

    @SerializedName("Val1")
    public String val1;

    @SerializedName("Val2")
    public String val2;

    public String id;

    public String pr;

    public String sid;

    public String cid;

    public String price;

    @SerializedName("cool_down")
    public String coolDown;

    public String url;

    public String name;
}

假设您正在使用GSON,那么当字段名称与JSON中的当前名称不同时,您应该只使用SerializedName注释。

有些应用程序会从JSON转换为POJO,例如Tyr