如何将多个JSONObjects放入/获取到JSONArray? [英] How to put/get multiple JSONObjects to JSONArray?

查看:757
本文介绍了如何将多个JSONObjects放入/获取到JSONArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将多个不同的JSONObject存储到单个JSONArray中?这是结构,我想存储在JSONArray中.

Is it possible to store multiple different JSONObjects into a single JSONArray? This is the structure, I want to store in a JSONArray.

[{"value1":1,"value2":900,"value3":1368349},{"value1":2,"value2":1900,"value3":136856},{"value1":3,"value2":600,"value3":136845}]

这是我设置JSONObject并将其放入JSONArray

Here's the code where I am setting JSONObject and putting it into a JSONArray

if(somecondition) {
  // putting values to json object
  jsonObj.put("value1", 1);
  jsonObj.put("value2", 900);
  jsonObj.put("value3", 1368349);
}
for(int i=0;i<=jsonArray.length();i++){
  jsonArray.put(jsonObj);
  appObj.setJsonAlarmArray(jsonArray);
  // appObj is object of Application Class
  editor= sharedPrefs.edit();
  editor.putString("key", jsonArray.toString());
  System.out.println(jsonArray.toString());
  editor.commit();
}

仅使用此代码的最后一个值,该值是我在JSON对象覆盖中设置的所有对象.有什么建议可以实现吗?

Using this code only the last value, which I am setting in JSON object Override to all objects. Any suggestions to achieve this?

推荐答案

我发现JSON的链接非常好:

I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object

这里是将多个JSONObject添加到JSONArray的代码.

Here's code to add multiple JSONObjects to JSONArray.

JSONArray Obj = new JSONArray();
try {
    for(int i = 0; i < 3; i++) {
        // 1st object
        JSONObject list1 = new JSONObject();
        list1.put("val1",i+1);
        list1.put("val2",i+2);
        list1.put("val3",i+3);
        obj.put(list1);
    }

} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}             
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();

这篇关于如何将多个JSONObjects放入/获取到JSONArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆