简体   繁体   中英

Json always returns null when parsing into POJO with gson

I have a Jackson server that Parses a Service object into JSON then sends it to Android. In Android, I have the same Service class but gson always returns a null object.

Service Class:

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 String:

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

Android Code:

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

The Json string is from the log so I know the server is working fine. The dependency is added in the module path of Gradle:

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

This test code worked without any problem:

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;
        }
    }
}

So, I think you should seek any other cause than Gson itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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