将JSON列表转换为GSON中的不同Java对象 [英] Converting JSON list as different Java Objects in GSON

查看:123
本文介绍了将JSON列表转换为GSON中的不同Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json字符串:

I have the following json string:

[
    {
        "question" : {
            "questionId" : 1109,
            "courseId" : 419
        },
        "tags" : ["PPAP", "testtest"],
        "choices" : [{
                "choiceId" : 0,
                "questionId" : 0
            }, {
                "choiceId" : 0,
                "questionId" : 0
            }
        ]
    }
]

我该如何制作问题,标记和选择使用GSON分隔对象?目前,我只使用 fromJson ,并且只能转换JSON字符串,如果它只包含1种类型的对象。

How do I make question, tags, and choices into separate objects using GSON? Currently I only use fromJson and can only convert a JSON string if it only contains 1 type of object.

推荐答案

您可以拥有以下类:

You can have following classes

class Question{
   questionId; //specify data type 
   courseId;
}
class Choice{
   choiceId;
   questionId;
}

然后你可以再定义一个类来存放所有三个成员变量

Then you can define one more class which will hold all the three member variables

class Extract{
 Question question;
 List<String> tags;
 List<Choice> choices;
} 

然后,您可以将此Extract类传递给 fromJson 方法,如

Then you can pass this Extract class to fromJson method like

List<Extract> result = gson.fromJson(jsonString, new TypeToken<List<Extract>>(){}.getType());

这篇关于将JSON列表转换为GSON中的不同Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆