【问题标题】:How to post this type of data in JSON Object如何在 JSON 对象中发布此类数据
【发布时间】:2019-04-11 18:29:07
【问题描述】:

我必须将这种类型的数据发布到 Json 中。我不想将 cat 转换为字符串。我只想要用双引号括起来的项目的单引号。

{"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}

我的 Json

      JSONObject jsonobject1 = new JSONObject();
        jsonobject.put("p02bvsd", "cal_dis");
        jsonobject.put("ovpsc7s", jsonobject1);
        jsonobject1.put("cat", hCategory);

这里的 hCategory 是 Hashset。

我想要这样的json

{"p02bvsd":"cal_dis","ovpsc7s":{"cat": ["'Furniture'", "'Bikes'", "'Others'" ]}}

【问题讨论】:

  • 你能用相关代码sn-ps分享你现在正在尝试的东西吗?你用什么来转换?
  • @brandonx 问题已更新,请查看
  • 请说明您当前获得的输出与期望的输出。
  • 好的,但是现在的输出是什么?
  • 我认为问题在于jsonobject1在添加到jsonobject之前正在被修改。

标签: java android arrays json


【解决方案1】:
JSONObject jsonobject = new JSONObject();
        jsonobject.put("p02bvsd", "cal_dis");
JSONObject jsonobject1 = new JSONObject();
List <String> list = new ArrayList <String>();
list.add("Furniture");
list.add("Bikes");
list.add("Others");

JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}

try {
    jsonobject1.put("cat", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}

jsonobject.put("ovpsc7s", jsonobject1);

【讨论】:

    【解决方案2】:
    String myString = "{\"p02bvsd\":\"cal_dis\",\"ovpsc7s\":{\"cat\":[\"\'Furniture\'\", \"\'Bikes\'\", \"\'Others\'\"]}}";
    
    JSONObject wholeThing = new JSONObject(myString); // contains {"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
    JSONObject jsonp02bvsd = wholeThing.getJSONObject("p02bvsd"); // contains {"p02bvsd":"cal_dis"}
    JSONObject jsonovpsc7s = wholeThing.getJSONObject("ovpsc7s"); // contains {"ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}
    JSONArray jsonCatArray = jsonp02bvsd.getJSONArray("cat");  // contains ["'Furniture'", "'Bikes'", "'Others'"]
    String first = jsonCatArray.getString(0); // contains 'Furniture'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多