[英]Deserializing inner class with gson returns null
我想使用 Gson 將我的 JSON 反序列化為對象。 我已經定義了適當的類,其中一些類的對象包含在其他對象中。 在嘗試反序列化整個 JSON 時,我得到了空值,因此我開始將其分解。
我達到了所有較低類都支持他們自己的地步,但是當嘗試反序列化為一個包含該較小對象實例的對象時 - 每件事都返回為 null。
我的部分 JSON:
{
"user_profile": {
"pk": 1,
"model": "vcb.userprofile",
"fields": {
"photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
"facebook_url": "https://google.com/facebook",
"site_name": "simple food",
"user": {
"pk": 1,
"model": "auth.user",
"fields": {
"first_name": "blue",
"last_name": "bla"
}
},
"site_url": "https://google.com/"
}
}
}
用戶配置文件類:
public class UserProfile {
private int pk;
private String model;
private UPfields fields = new UPfields();//i tried with and without the "new"
}
UPfields 類:
public class UPfields {
private String photo;
private String facebook_url;
private String site_name;
private User user;
private String site_url;
}
用戶類別:
public class User {
private int pk;
private String model;
private Ufields fields;
}
Ufields 類:
public class Ufields {
private String first_name;
private String last_name;
}
在我的主要我打電話:
Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);
所以我的臨時對象只包含空值。 我試過將類更改為靜態,但它不起作用。 UPfields 對象和所有較低的對象都可以正常工作。
有什么建議?
當我刪除
"{
"user_profile":"
它是右括號,反序列化為 user_profile 對象有效。
為了解析這個json
示例,您必須創建輔助類,該類將包含名為UserProfile
類型的user_profile
字段:
public class UserProfileWrapper {
private UserProfile user_profile;
}
並使用此類解析此json
字符串:
UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);
Gson 首先解析最外面的對象,在您的情況下,它只有一個字段user_profile
。 您的UserProfile
類沒有user_profile
字段,因此無法將其反序列化為該類的實例。 您應該嘗試反序列化user_profile
字段的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.