0

我的代码是:

 JSONObject jChild=new JSONObject();
         JSONObject jParent=new JSONObject();
            for (Product p : boxAdapter.getBox()) {
              if (p.checked){
                try {
                    jChild.put("uid", p.uid);
                list.add(String.valueOf(jChild));

                    //list.add(String.valueOf(jParent));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
              }
            }
            jParent.put("users", list);

          // Toast.makeText(this, ""+jParent, Toast.LENGTH_LONG).show();
            Log.v("TakeAttendance","JSONpARENT "+String.valueOf(jParent));

输出 :

{"users":"[{\"uid\":\"4\"}, {\"uid\":\"5\"}, {\"uid\":\"6\"}]"}

我真正需要的:

  {users: [
    {
    name: "acx",
    uid: "2"
    },

    {
    name: "test",
    uid: "6"
    },

    {
    name: "ccc",
    uid: "11"
    }
    ]
    }
4

4 回答 4

1

JSON 要求键和值都是字符串。如果您需要漂亮的打印 JSON 对象,请尝试pretty-print-json-in-java

于 2013-09-05T05:14:53.693 回答
0

正确的 JOSNObject 将是

     {"users": [

    {
    "name": "acx",
    "uid": "2"
    },

    {
    "name": "test",
    "uid": "6"
    },

    {
    "name": "ccc",
    "uid": "11"
    }
  ]

}

String data ; // JOSN String
JSONObject data = new JSONObject(data);
JSONArray array = data.getJSONArray("users");
for(int i=0; i<array.length; i++){
        JSONObject obj = array.getJSONObject(i);
        String name = obj.getString("name");
        String uid  = obj.getString("uid");
}

从数据生成

            JSONObject parent = new JSONObject(); 
            JSONArray list = new JSONArray ();
            for (Product p : boxAdapter.getBox()) {
              if (p.checked){
                try {
                     JSONObject jChild=new JSONObject();
                     jChild.put("uid", p.uid);
                     jChild.put("name", p.name);
                     list.add(String.valueOf(jChild));

                }
                catch (JSONException e) {
                    e.printStackTrace();
                }

              }
            }
            jParent.put("users", list);
于 2013-09-05T05:02:12.230 回答
0

你得到的实际上是正确的 JSON。它将被正确解析回 JSON 对象。如果您只想将其仅用于打印目的,则可以将 '\"' 替换为空白字符串。

于 2013-09-05T06:23:01.197 回答
0

如果列表是JSONArray..

         JSONObject jParent=new JSONObject();
         JSONArray list = new JSONArray();
         try {
            for (Product p : boxAdapter.getBox()) {                  
              if (p.checked){
                JSONObject jChild=new JSONObject(); //Correction here   
                    jChild.put("uid", p.uid);
                list.add(jChild);        //Correction here                       

              }
            }
            jParent.put("users", list);    
           } catch (JSONException e) {
                    e.printStackTrace();
                }

            Log.v("TakeAttendance","JSONpARENT "+jParent); //Correction here
于 2013-09-05T04:51:39.043 回答