从java中的json对象获取正确的输出
我的代码是:从java中的json对象获取正确的输出,java,android,json,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);
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"
}
]
}
如果列表是
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
正确的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");
}
JSON要求键和值都是字符串。如果您需要漂亮的打印JSON对象,请尝试获得正确的JSON。它将被正确解析回JSON对象。如果只想打印,可以用空白字符串替换“\”。JSON要求键和值都是字符串。如果需要pretty print JSON对象,请尝试将其格式化并获得正确的输出,如上图所示。Log.v()应该打印我需要的数据。您没有放置
name
属性,因此您的输出显然没有它
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);