相关疑难解决方法(0)

当要解析的元素是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; …
Run Code Online (Sandbox Code Playgroud)

java serialization parsing json gson

12
推荐指数
1
解决办法
5063
查看次数

标签 统计

gson ×1

java ×1

json ×1

parsing ×1

serialization ×1