简体   繁体   English

将pojo映射到json时为nullpointerexception

[英]nullpointerexception on mapping pojo to json

{
   "App":[{
        "AppID": 0,
        "AppTime": "08:00 AM"
    }],
   "Rows": 0
}

Here is my JSON Response, but when i map to my POJO class and access i get a NullPointerException . 这是我的JSON响应,但是当我映射到POJO类并访问时,我得到了NullPointerException

ListResponse value = new Gson().fromJson(result, ListResponse.class);

import java.util.List;
public class ListResponse{

    public List<AppList> appList;

    public List<AppList> getAppList() {
        return appList;
    }
}

When i try to access my result in my activity class, like this i get an error. 当我尝试在活动类中访问我的结果时,像这样,我得到一个错误。

public void accessData(ListResponse result){
    System.out.println(result.getAppList()); // I am getting null here.
}

Update: 更新:

My AppList Class contains, AppID, AppTime and Rows. 我的AppList类包含AppID,AppTime and行。

I think you are storing your response in value 我认为您的回应是value

 ListResponse value = new Gson().fromJson(result, ListResponse.class);

Hence try calling value.getAppList() : 因此,尝试调用value.getAppList()

 public void accessData(ListResponse result){
    System.out.println(value.getAppList()); // shouldn't get NullPointer
 }

Also its good idea to put a null check, if the value could possibly be null as: 如果值可能为null ,则进行null检查也是一个好主意,例如:

 public void accessData(ListResponse result){
    if(value != null){
        System.out.println(value.getAppList()); // shouldn't get NullPointer
     }else{
        System.out.println("value is null");
     }
 }

When you use GSon to translate a String to an Object (in your case the ListResponse object), the names of the attributes in this class need to be exactly the same value in the keys of the json string. 当您使用GSon将String转换为对象(在您的情况下为ListResponse对象)时,此类的属性名称必须与json字符串键中的值完全相同。

The problem in your case: The key in json is "App": 您遇到的问题:json中的键是“ App”:

"App":[{
    "AppID": 0,
    "AppTime": "08:00 AM"
}],

And the attribute name is appList . 属性名称为appList Try put appList in the json, or change to public List<AppList> App; 尝试将appList放在json中,或更改为public List<AppList> App; in the class. 在课堂里。 This should solve the null. 这应该解决null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM