【问题标题】:Json always returns null when parsing into POJO with gson使用 gson 解析成 POJO 时,Json 总是返回 null
【发布时间】:2021-06-02 15:18:27
【问题描述】:

我有一个 Jackson 服务器,可以将 Service 对象解析为 JSON,然后将其发送到 Android。在 Android 中,我有相同的 Service 类,但 gson 总是返回一个空对象。

服务类:

public class Service {
    public String ServiceName;
    public ArrayList<String> ParamList;
    public ArrayList<String> ParamType;

    public Service(String sn,ArrayList<String> pl,ArrayList<String> pt) {
        this.ServiceName = sn;
        this.ParamList = pl;
        this.ParamType = pt;
        // TODO Auto-generated constructor stub
    }

JSON 字符串:

{"ParamList":[],"ParamType":[],"ServiceName":"ServiceX"}

安卓代码:

gson.fromJson(response,Client.Service.class)

Json 字符串来自日志,所以我知道服务器工作正常。在 Gradle 的模块路径中添加依赖:

    implementation 'com.google.code.gson:gson:2.8.6'

【问题讨论】:

  • 在将response 传递给fromJson 之前,您是否确定您的response 不为空或null?

标签: java android json gson


【解决方案1】:

这个测试代码没有任何问题:

public class Main {
    public static void main(String[] args) {
        Service service = new Gson().fromJson(
                "{\"ParamList\":[],\"ParamType\":[],\"ServiceName\":\"ServiceX\"}",
                Main.Service.class
                );
        
        System.out.println(service.ServiceName);
    }
    
    public static class Service {
        public String ServiceName;
        public List<String> ParamList;
        public List<String> ParamType;

        public Service(String sn, List<String> pl, List<String> pt) {
            this.ServiceName = sn;
            this.ParamList = pl;
            this.ParamType = pt;
        }
    }
}

所以,我认为你应该寻求 Gson 本身以外的任何其他原因。

【讨论】:

  • 这是 Android Studio 的环境问题。重新构建项目并再次添加依赖项,它工作了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2013-02-02
  • 2011-04-26
  • 2013-08-15
  • 2018-04-01
相关资源
最近更新 更多