繁体   English   中英

将 Key 值添加到从 GSON.toJSON 生成的 Json String

[英]Add a Key value to Json String generated from GSON.toJSON

  String jsonResponse=Utils.getGsonInstance().toJson(Object);

jsonResponse 返回:

[
   {
    "Key":"1",
    "Code": "11",
   },
   {    
    "key":"2",
    "code": "22",
    }
]

我正在寻找的最终结果是将此 JSON-String 包装在另一个 Key Eg 中

{
 "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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM