使用对象名称android创建JSON数组

时间:2017-01-24 19:04:17

标签: android json android-studio

我想像这样创建JSONArray

enter image description here

当我在数组中添加json对象时,它会像这样格式化

enter image description here

我的代码:

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);

2 个答案:

答案 0 :(得分:2)

您处于两种模式之间,您可以将其用作地图或数组。

地图方法:

{
  "steps": { "steps":123, "time": 123 },
  "calories": { and so},
  "bpm": { on }
}

代码(未经测试,思考和调整)

// 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);

答案 1 :(得分:0)

不,您无法在JSONArray中添加密钥。你可以在JSONObject中做到这一点。

两种方法:

  1. 使用JSONArray(像列表一样行事):

    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);
    
  2. 使用JSONObject(像地图/字典一样):

    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);
    
  3. 小心你的价值观。 “12313”是一个字符串,而345是一个整数。