String jsonResponse=Utils.getGsonInstance().toJson(Object);
jsonResponse 返回:
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
我正在寻找的最终结果是将这个 JSON 字符串包装在另一个键中,例如
{
"MainObj":
[
{
"Key":"1",
"Code": "11",
},
{
"key":"2",
"code": "22",
}
]
}
有没有办法使用 GSON Api 来实现这一点?
我试过了::
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
我得到的输出是:
{"MainObj": "[{\"Key\":\"1",\"Code\":\"11\"}, {\"Key\":\"2",\"Code\":\"22\"}]"}
最佳答案
继续使用 GSON,如下所示:
public class MainObj {
@SerializedName("MainObj")
public List<Key> Main;
public class Key {
@SerializedName("Key")
public String Key;
@SerializedName("code")
public String Code;
}
}
然后改变
JSONObject jsonObject = new JSONObject();
jsonObject.put("MainObj",jsonResponse);
由
String tmp = new Gson().toJson(new MainObj());
关于java - 将 Key 值添加到 GSON.toJSON 生成的 Json 字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193326/