Reputation: 8149
I want to create JSONArray
like this
when i add json object in array it will format like this
My Code:
JSONObject object = new JSONObject();
object.put("calories_burn", "345");
object.put("time", dp.getTimestamp(TimeUnit.MILLISECONDS));
JSONObject object1 = new JSONObject();
object1.put("calories", object);
array.put(object1);
Upvotes: 0
Views: 10720
Reputation: 1995
No, you cannot add keys inside a JSONArray. You can do that inside a JSONObject though.
Two approaches:
With JSONArray (Acts Like A List):
JSONArray jsonArray = new JSONArray();
JSONObject caloriesJSON = new JSONObject();
caloriesJSON.put("calories_burn", 345);
caloriesJSON.put("time", dp.getTimestamp(TimeUnit.MILLISECONDS));
JSONObject stepsJSON = new JSONObject();
stepsJSON.put("steps", "12121");
stepsJSON.put("time", dp.getTimestamp(TimeUnit.MILLISECONDS));
jsonArray.put(stepsJSON);
jsonArray.put(caloriesJSON);
With JSONObject(Acts Like A Map/Dictionary):
JSONObject jsonObject = new JSONObject();
JSONObject caloriesJSON = new JSONObject();
caloriesJSON.put("calories_burn", 345);
caloriesJSON.put("time", dp.getTimestamp(TimeUnit.MILLISECONDS));
JSONObject stepsJSON = new JSONObject();
stepsJSON.put("steps", "12121");
stepsJSON.put("time", dp.getTimestamp(TimeUnit.MILLISECONDS));
jsonObject.put("steps", stepsJSON);
jsonObject.put("calories", caloriesJSON);
Be careful what you put for values. "12313" is a String whereas 345 is an integer.
Upvotes: 0
Reputation: 1420
You are falling in between two patterns, you can either use it as a map, or an array.
Map approach:
{
"steps": { "steps":123, "time": 123 },
"calories": { and so},
"bpm": { on }
}
Code (untested, think and tweak)
// Build your objects
JSONObject steps = new JSONObject();
steps.put("steps", 123);
steps.put("time" 123);
JSONObject calories = new JSONObject();
//And so on
JSONObject bpm = new JSONObject();
//Make a map
JSONObject map = new JSONObject();
//Add to the map:
map.put("steps", steps);
map.put("calories", calories);
map.put("bpm", bpm);
Upvotes: 2