从java中的json对象获取正确的输出

时间:2013-09-05 04:42:06

标签: java android json

我的代码是:

 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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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

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

答案 3 :(得分:0)

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