my code is:
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));
Output :
{"users":"[{\"uid\":\"4\"}, {\"uid\":\"5\"}, {\"uid\":\"6\"}]"}
What i actually need :
{users: [
{
name: "acx",
uid: "2"
},
{
name: "test",
uid: "6"
},
{
name: "ccc",
uid: "11"
}
]
}
JSON requires both key and value are strings. If you need pretty print JSON object, try pretty-print-json-in-java
If list is 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
Correct JOSNObject will be
{"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");
}
For generating from Data
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);
What you are getting is actually correct JSON. It will be parsed back to a JSON object correctly. If you want this only for printing purpose, you can just replace '\\"' with blank string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.