[英]Using Gson on a class that is defined into method returns null
我有一個只需要在一個方法中使用的類..所以我已經在方法中聲明了它。
現在,當我嘗試使用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字符串。
根據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
類,這樣就可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.