我对JSON/GSON非常陌生,所以如果这是一个非常简单的问题,我很抱歉。我一直在尝试使用GSON在Android中创建嵌套JSON。
下面是我要创建的内容:
{"choice": {"question_id":"1", "answer_id":"2", "survey_id":"1"}}
然而,我的Android代码的输出是在大括号周围有圆括号和许多额外的's:
{"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是有效的,但当我用它来发布到我的服务器时,它似乎不起作用。
提前感谢!
编辑:我发现为什么Gson。toJson将泛型字段序列化为空JSON对象,该对象提到了对泛型类型的序列化和反序列化。这指出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输出。
我已经尝试使用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关于嵌套对象,嵌套列表,似乎当你从对象生成json字符串时,你不需要比新的Gson(). tojson(对象)更多的东西。(即使你的对象有嵌套的List属性!)只有当你试图将List生成为Json时,才需要使用TypeToken。
简而言之,使用Gson库生成json字符串如下:
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库的java中自己尝试。它真的很容易使用!