使用android </t>中的List <t>从Json String获取数据

时间:2014-02-01 12:11:37

标签: java android json

我使用List<t>从Json String获取数据。

我能够获得问题和数据的数据。 QId但是选项是json字符串里面的json字符串。所以我对如何获取这些数据感到困惑。

我获取数据的示例代码:

Test[] placelist = gson.fromJson(result, Test[].class);
List<Test> lList = Arrays.asList(placelist);
Test obj = lList.get(i);
obj.getQuestion();

测试是Java类文件,其中包含获取和获取的方法。设定数据。

我的Json字符串:

 [
    {
        "Question": "Are you inclined to",
        "QId": "2",
        "Options": [
            {
                "Option": "Argue or debate issues",
                "OptionId": "4"
            },
            {
                "Option": "Avoid arguments",
                "OptionId": "5"
            },
            {
                "Option": "Swutch topics",
                "OptionId": "6"
            }
        ]
    },
    {
        "Question": "Are you more likely to trust",
        "QId": "3",
        "Options": [
            {
                "Option": "Yourself",
                "OptionId": "7"
            },
            {
                "Option": "Reason",
                "OptionId": "8"
            },
            {
                "Option": "Feeling",
                "OptionId": "9"
            }
        ]
    },
    {
        "Question": "Would you say that you",
        "QId": "4",
        "Options": [
            {
                "Option": "Make decisions easily",
                "OptionId": "10"
            },
            {
                "Option": "Find difficulties to make decision",
                "OptionId": "11"
            },
            {
                "Option": "Wait for some conclusions",
                "OptionId": "12"
            }
        ]
    }
]

测试类:

public class Test{

    private String Question;
    private String Option;

    public Test(String Question, String Option) {
        this.Question= Question;
        this.Option= Option;
    }

    public void setQuestion(String Question) {
        this.Test= Question;
    }

    public void setOption(String Option) {
        this.Option= Option;
    }

    public String getQuestion() {
        return this.Question;
    }

    public String getOption() {
        return this.Option;
    }
}

我不确定要使用什么代替setOption()&amp; getOption()获取选项。
请帮我获取选项数据。

2 个答案:

答案 0 :(得分:0)

您的Test类有几个明显的问题:

  1. “选项”是您的JSON中的“选项”,您需要重命名或注释它。
  2. Options是Test类中的String类型,但实际上是JSON数据中的数组。您需要创建一个Option类,并将Test类中的类型更改为List&lt; Option&gt ;.

答案 1 :(得分:0)

您可以使用gson来获取数据。 步骤进行:

1. Create the test class such that it has question,id as string 
and Option as a list of options, and Test is going to be a list of Test
2. Use @SerializedValue in order to map the fields correctly.
3. Refer to :

this了解如何使用gson