简体   繁体   English

在定义到方法中的类上使用Gson返回null

[英]Using Gson on a class that is defined into method returns null

I'm have a class that i only need in one method.. so i have declared it in the method. 我有一个只需要在一个方法中使用的类..所以我已经在方法中声明了它。

and now when i try to convert an object from this class to json using gson i get null. 现在,当我尝试使用gson将此类中的对象转换为json时,我得到了null。

my code is something like this: 我的代码是这样的:

private Response performGetClientDetails(HashMap<String, Object> requestMap) {

        class ClientDetails {
            String id;
            String name;
            String lastName;
            int accoundId;

            public ClientDetails(String id, String name, String lastName, int accoundId) {
                this.id = id;
                this.name = name;
                this.lastName = lastName;
                this.accoundId = accoundId;
            }
        }

        ClientDetails clientDetails = new ClientDetails(client.getId(), client.getFirstName(), client.getLastName(), client.getAccount().getId());
        Gson gson = new Gson();
        return new Response(true, gson.toJson(clientDetails));
    }

what is returning null is this: gson.toJson(clientDetails) .. its supposed to return a json string. 返回null是什么: gson.toJson(clientDetails) ..它应该返回json字符串。

According to GSON Docs : 根据GSON Docs的说法:

" Gson can not deserialize {"b":"abc"} into an instance of B since the class B is an inner class. if it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B. " Gson can not deserialize {"b":"abc"} into an instance of B since the class B is an inner class. if it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.

public class InstanceCreatorForB implements InstanceCreator<A.B> {
  private final A a;
  public InstanceCreatorForB(A a)  {
    this.a = a;
  }
  public A.B createInstance(Type type) {
    return a.new B();
  }
}

The above is possible, but not recommended.

Since you're using a non-static inner class, Gson will not be able to serialize the object. 由于您使用的是非静态内部类,因此Gson将无法序列化该对象。

You can try the second solution, which is not recommended, to use on your case or simply declare the ClientDetails class by itself, which will work fine. 您可以尝试不建议使用的第二种解决方案,以用于您的案例,或者只是自己声明ClientDetails类,这样就可以正常工作。

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

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