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

时间:2013-04-23 20:39:30

标签: java json class null gson

我有一个我只需要在一个方法中的类..所以我在方法中声明了它。

现在当我尝试使用gson将对象从此类转换为json时,我得到null。

我的代码是这样的:

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

返回null的是:gson.toJson(clientDetails) ..它应该返回一个json字符串。

1 个答案:

答案 0 :(得分:5)

根据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.

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.

由于您使用的是非静态内部类,Gson将无法序列化该对象。

您可以尝试使用不推荐的第二个解决方案,或者只是单独声明ClientDetails类,这样可以正常工作。