杰克逊,在List<>获得null返回

时间:2017-06-27 13:13:46

标签: java android json jackson

我不明白为什么要返回null

有两个关于Jackson和String Volley请求的课程

StringRequest request = new StringRequest(Request.Method.GET,regions, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG,"response"+ response);
            try {
                ObjectMapper mapper=new ObjectMapper();
                Pojo pojo=mapper.readValue(response,Pojo.class);
                System.out.println(pojo.toString());
            }catch (IOException e) {
                e.printStackTrace();
            }

Json

{
  "success": true,
  "data": [
    {
        "id": "1",
        "name": "RegionABC"
    },
    {
        "id": "2",
        "name": "RegionDEF"
    },
  ]
}

它由2个类解析:

Pojo

public class Pojo {
public Pojo(){}
private boolean success;
private List<Pojo> data;

@JsonProperty("data")
public List<Pojo> getDataPojo() {
    return data;
}

public void setDataPojo(List<Pojo> data) {
    this.data = data;
}

// getters & setters
@JsonProperty("success")
public boolean isSuccessPojo() {
    return success;
}

public void setSuccessPojo(boolean success) {
    this.success = success;
}
@Override
public String toString() {
    return "data "+data;
}

DataPojo

public class DataPojo {
private String id, name;

public String getIdDataPojo() {
    return id;
}

public void setIdDataPojo(String id) {
    this.id = id;
}

public String getNameDataPojo() {
    return name;
}

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

我的代码在哪里?它仅适用于简单的字符串,但使用List<> - 否。

1 个答案:

答案 0 :(得分:0)

在您的代码中找到此部分:

@JsonProperty("data")
public List<Pojo> getDataPojo() {
    return data;
}
public void setDataPojo(List<Pojo> data) {
    this.data = data;
}

并替换为此代码:

@JsonProperty("data")
public List<DataPojo> getDataPojo() {
    return data;
}
public void setDataPojo(List<DataPojo> data) {
    this.data = data;
}