Android嵌套JSON与GSON

时间:2014-03-20 01:57:00

标签: android json gson

我对JSON / GSON很新,所以如果这是一个非常简单的问题我会道歉。我一直在尝试使用GSON在Android中创建嵌套的JSON。

以下是我要创建的内容:

{"choice": {"question_id":"1", "answer_id":"2", "survey_id":"1"}}

然而,我的Android代码输出的输出在内括号周围有括号,还有很多其他的:

{"choice":"{\"question_id\":\"1\",\"survey_id\":\"1\",\"answer_id\":\"1\"}"}

以下是我如何生成JSON:

Map<String, String> choice = new HashMap<String, String>();
        choice.put("question_id", "1");
        choice.put("answer_id", "1");
        choice.put("survey_id", "1");
        String json = new GsonBuilder().create().toJson(choice, Map.class);

        Map<String, String> choices = new HashMap<String, String>();
        choices.put("choice", json);
        String jsonChoice = new GsonBuilder().create().toJson(choices, Map.class);
        Log.i("JSON", "JSON is: " + jsonChoice);

有没有更好的方法来创建嵌套的JSON对象?反斜杠实际上做了什么或者那些可以吗? jsonlint.com说json是有效的,但是当我用它发布到我的服务器时,它似乎不起作用。

提前致谢!

修改

我发现Why does Gson.toJson serialize a generic field to an empty JSON object提及serializing and deserializing generic types。这指出Map.class不会起作用,因为它没有参数化,或者说Gson不知道它是Map。所以这是我的更新代码:

Type listType = (Type) new TypeToken<Map<String, String>>() {}.getType();

        Map<String, String> choice = new HashMap<String, String>();
        choice.put("question_id", "1");
        choice.put("answer_id", "1");
        choice.put("survey_id", "1");
        String json = new GsonBuilder().create().toJson(choice, listType);

        Map<String, String> choices = new HashMap<String, String>();
        choices.put("choice", json);
        String jsonChoice = new GsonBuilder().create().toJson(choices, listType);
        Log.i("JSON", "JSON is: " + jsonChoice); 

但不幸的是,它仍然提供与以前相同的JSON输出。

1 个答案:

答案 0 :(得分:1)

我尝试使用Gson创建json对象或将json解码为javabean,并成功获得所需的结果,以下是我尝试的内容:

public class Choice {
    private ChoiceDetail choice;
    public Choice(ChoiceDetail choice) {
        super();
        this.choice = choice;
    }

}

class ChoiceDetail{
    private String question_id;
    private String answer_id;
    private String survey_id;
    public ChoiceDetail(String question_id, String answer_id, String survey_id) {
        super();
        this.question_id = question_id;
        this.answer_id = answer_id;
        this.survey_id = survey_id;
    }

}

public class TestGson {

    public static void main(String[] args) {
        ChoiceDetail detail = new ChoiceDetail("1","2","3");
        Choice choice = new Choice(detail);
        Gson g = new Gson();
        String json = g.toJson(choice);
        System.out.println(json);
    }
}

我测试了Gson关于嵌套对象,嵌套列表的问题,当你从Object生成一个json字符串时,你似乎不需要新的Gson()。toJson(object)。(即使是您的对象具有嵌套的List属性!)只有当您尝试生成List to Json时,才需要使用TypeToken。

简而言之,使用Gson lib生成json String就像这样:

String json = new Gson().toJson(object or List<object>)

将json字符串解码为对象就像这样

对象:

ModelA modela  = g.fromJson(json, ModelA.class);

列表:

List<ModelA> list = g.fromJson(json, new TypeToken<List<ModelA>>(){}.getType());

您可以在包含Gson lib的JavaSE中自己尝试。它真的很容易使用!