当要解析的元素是json字符串的元素时,使用gson解析json的最简单方法是什么?

我正在使用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(); }