Reputation: 1707
I need to make JSON like this on android -
{
"Warp":[
{
"Type":"Cotton",
"Property":"Carded",
"Count":"10"
},
{
"Type":"Cotton",
"Property":"Carded",
"Count":"10"
}
]
}
I tried
j = new JSONObject();
j2.put("Type", "Cotton");
j2.put("Property", "Carded");
j2.put("Count", "10");
a = new JSONArray();
a.put("Warp", j2);
But looks like I cannot directly put an JSONArray inside a JSONObject like this.
Any help is appreciated.
Upvotes: 0
Views: 129
Reputation: 667
You can use easily like this
try {
JSONObject root = new JSONObject();
JSONArray wrap = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject wrapObj = new JSONObject();
wrapObj.put("Count", "10");
wrapObj.put("Property", "Carded");
wrapObj.put("Type", "Cotton");
wrap.put(wrapObj);
}
root.put("Warp", wrap);
} catch (JSONException e) {
e.printStackTrace();
}
Don't forgot to put your code in try-catch block.
Upvotes: 0
Reputation: 2623
public JSONObject createGroupInServer() throws JSONException {
JSONObject jResult = new JSONObject();
JSONArray jArray = new JSONArray();
for (int i = 0; i < ArrayList.size(); i++) {
JSONObject jGroup = new JSONObject();
jGroup .put("Type", "Cotton");
jGroup .put("Property", "Carded");
jGroup .put("Count", "10");
jArray.put(jGroup);
}
jResult.put("Warp", jArray);
return jResult;
}
Upvotes: 0
Reputation: 101
Do Something like this :
try {
JSONObject mainObject = new JSONObject();
JSONArray array = new JSONArray();
JSONObject object1 = new JSONObject();
JSONObject object2 = new JSONObject();
object1.put("Type", "Cotton");
object1.put("Property", "Carded");
object1.put("Count", "10");
object2.put("Type", "Cotton");
object2.put("Property", "Carded");
object2.put("Count", "10");
array.put(object1);
array.put(object2);
mainObject.put("Warp", array);
} catch (JSONException e){
e.printStackTrace();
}
Upvotes: 1
Reputation: 35539
you cannot put JsonObject
with key
inside JsonArray
, JsonArray
will hold all JsonObject without key.
JSONArray warpArray=new JSONArray();
JSONObject inner=new JSONObject();
inner.put("Type", "Cotton");
inner.put("Property", "Carded");
inner.put("Count", "10");
warpArray.put(inner);
JSONObject mainJson=new JSONObject();
mainJson.put("Warp",warpArray);
Upvotes: 0
Reputation: 4025
Do it like this:
// Create object
JSONObject objectInArray = new JSONObject();
objectInArray.put("Type", "Cotton");
objectInArray.put("Property", "Carded");
objectInArray.put("Count", "10");
// Create array and add the object
JSONArray array = new JSONArray();
array.put(objectInArray);
// Create the object and add the array on "wrap"
JSONObject wrapObject = new JSONObject();
wrapObject.put("wrap", array);
Upvotes: 0
Reputation: 837
try this
j = new JSONObject();
j2.put("Type", "Cotton");
j2.put("Property", "Carded");
j2.put("Count", "10");
a = new JSONArray();
a.put(j2);
j.put(a);
Upvotes: 0