1

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

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

我的代码是这样的:

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字符串。

4

1 回答 1

5

根据GSON 文档

" 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自行声明该类,这将正常工作。

于 2013-04-23T21:03:07.917 回答