将JSON数据添加到arrayList

时间:2011-07-26 03:13:02

标签: java android json arraylist

仍在处理我脚本的这一部分,以解析我的JSON jsonArray = new JSONArray(jsonData);,然后将其添加到arraylist“myJSONArray”

我不确定for循环如何将我的元素从jsonArray添加到myJSONArray(arrayList)

如果我不清楚,请告诉我,如果有任何信息,我想知道。提前谢谢。

JSON数据:

{"id":["1","2","3"],"name":["Dragon","Butterfly","Tattoo"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}

image_data class:

public class image_data {


    public int id;
    public String name;
    public String thumb;
    public String path;


}

ShowThumb类:

public class showThumb extends Activity{



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridlayout);

         Bundle bundle = getIntent().getExtras();
         String jsonData = bundle.getString("jsonData");


         JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(jsonData);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ArrayList<image_data> myJSONArray = new ArrayList<image_data>();

         for (int i=0; i<jsonArray.length(); i++) {
               **//This is where I think I create the seperate arrays of id name thumb and path**
             myJSONArray.add(new image_data());

         }


GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this,image_data));

    }
}

2 个答案:

答案 0 :(得分:4)

如何迭代和添加

 for(int i=0;i<jsonArray.length;i++)
    {    
         JSONObject json_data = jArray.getJSONObject(i);
         imgnfo.id =  json_data.getInt("id_key");
         imgnfo.name = json_data.getString("name_key");
         imgnfo.thumb = json_data.getString("thumb_key");
         imgnfo.info = json_data.getString("info_key");
         myArray.add(new image_data());
    }

只需添加正确的密钥名称即可。我不知道他们。

答案 1 :(得分:2)

哟应该发布json数据的样子。 假设json数据看起来像

...,{
    "image_data": {
        "name": "image name","thumb":"thumbpath","path":"path"}
},{
    "image_data": {
        "name": "image name 2","thumb":"thumbpath 2","path":"path 2"}
}

然后你会像这样提取值:

    ArrayList<image_data> imageArray = new ArrayList<image_data>();

         for (int i=0; i<jsonArray.length(); i++) {
             image_data img = new image_data();

             Object jo = jsonArray.get(i);

             image_data.name = jo.name;
             image_data.thumb = jo.thumb;
             image_data.path = jo.path;

             imageArray.add(new image_data());

         }

考虑为你使用getter image_data类。 还可以考虑将其重命名为ImageData