[英]What is the easiest way to parse json using gson when the element to parse is an element of a json string?
我正在使用gson將json解析為java bean。 對於我使用的API,大量的json結果將結果包含為json對象的第一個屬性。 “gson方式”似乎是創建一個等效的包裝器java對象,它有一個目標輸出類型的屬性 - 但這會導致不必要的一次性類。 這樣做有最佳實踐方法嗎?
例如要解析: {"profile":{"username":"nickstreet","first_name":"Nick","last_name":"Street"}}
我要做:
public class ParseProfile extends TestCase {
public void testParseProfile() {
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
String profileJson = "{\"profile\":{\"username\":\"nickstreet\",\"first_name\":\"Nick\",\"last_name\":\"Street\"}}";
ProfileContainer profileContainer = gson.fromJson(profileJson, ProfileContainer.class);
Profile profile = profileContainer.getProfile();
assertEquals("nickstreet", profile.username);
assertEquals("Nick", profile.firstName);
assertEquals("Street", profile.lastName);
}
}
public class ProfileContainer {
protected Profile profile;
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
public class Profile {
protected String username;
protected String firstName;
protected String lastName;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
當然,使用容器的另一種方法是使用標准的字符串解析技術手動刪除字符串的外部部分(即刪除“profile”:{和closing}),但這感覺就像錯誤的方法。
我希望能夠做到這樣的事情:
Profile p = gson.fromJsonProperty(json, Profile.class, "profile");
這個問題表明應該可以將json字符串分解為json對象,從該對象中提取jsonElement,並將其傳遞給json.fromJson()。 但是,toJsonElement()方法僅適用於java對象,而不適用於json字符串。
有沒有人有更好的方法?
我遇到了同樣的問題。 基本上你要做的就是避免所有容器類的廢話只是使用JSONObject函數來檢索你試圖反序列化的內部對象。 請原諒我的代碼,但它是這樣的:
GsonBuilder gsonb = new GsonBuilder()
Gson gson = gsonb.create();
JSONObject j;
JSONObject jo;
Profile p = null;
try {
j = new JSONObject(convertStreamToString(responseStream));
jo = j.getJSONObject("profile"); // now jo contains only data within "profile"
p = gson.fromJson(jo.toString(), Profile.class);
// now p is your deserialized profile object
}catch(Exception e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.