如何在JSON对象中发布此类数据

时间:2019-04-11 18:29:08

标签: java android arrays json

我必须将这种类型的数据发布到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是哈希表。

我想要这样的json

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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'