android - 多级 JSON 解析

标签 android json parsing

我正在编写多级 json 解析程序,并且能够获取一级列表,但在点击一级列表项时不显示二级列表。

简而言之,我列出的类别在尝试列出点击类别的视频时遇到了问题。

我正在做这样的事情:

Main Activity [Listing Categories] > Another Activity [Listing Videos]

MainActivity.java:

static String NAME = "name";
static String THUMB = "thumb";    
.............................
        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("categories");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("name", jsonobject.getString("name"));
                map.put("thumb", jsonobject.getString("thumb"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

MainAdapter.java:

        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, AnotherActivity.class);
                // Pass name
                intent.putExtra("name", resultp.get(MainActivity.NAME));
                // Start AnotherActivity Class
                context.startActivity(intent);

            }
        });
        return itemView;
    }

注意:使用上面的代码获取类别列表

AnotherActivity.java-

 static String THUMB = "thumb";
 static String TITLE = "title";
 static String SUBTITLE = "subtitle";    
 static String DESCRIPTION = "description";
 ........................
            try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("videos");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                final JSONArray sources = jsonobject.getJSONArray("sources");
                // Retrive JSON Objects
                map.put("title", jsonobject.getString("title"));
                map.put("thumb", jsonobject.getString("thumb"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

Manifest.xml:-

<activity android:name="com.example.zing.AnotherActivity" />

JSON:

{
    "categories": [
        {
            "name": "Dev Events",
            "thumb": "http://www.androidbegin.com/tutorial/flag/unitedstates.png",
            "videos": [
                {
                    "sources": [
                        "http://commondatastorage.googleapis.com/gtv_template_assets/IO2010-Keynote-day1.mp4"
                    ],
                    "thumb": "http://www.androidbegin.com/tutorial/flag/unitedstates.png",
                    "title": "2010 Day 1 Keynote",
                    "subtitle": "Dev Events",
                    "description": "IO2010 Keynote"
                },
                {
                    "sources": [
                        "http://commondatastorage.googleapis.com/gtv_template_assets/IO2010-Keynote-day2-android.mp4"
                    ],
                    "thumb": "http://www.androidbegin.com/tutorial/flag/russia.png",
                    "title": "2010 Day 2 Keynote",
                    "subtitle": "Dev Events",
                    "description": "IO2010 Keynote Android"
                }
            ]
        },
        {
            "name": "Technology",
            "thumb": "http://www.androidbegin.com/tutorial/flag/russia.png",
            "videos": [
                {
                    "sources": [
                        "http://commondatastorage.googleapis.com/gtv_template_assets/CWS-HowTo.mp4"
                    ],
                    "thumb": "http://www.androidbegin.com/tutorial/flag/russia.png",
                    "title": "Uploading your App",
                    "subtitle": "Technology",
                    "description": "CWS HowTo"
                },
                {
                    "sources": [
                        "http://commondatastorage.googleapis.com/gtv_template_assets/CWS-GettingStarted.mp4"
                    ],
                    "thumb": "http://www.androidbegin.com/tutorial/flag/unitedstates.png",
                    "title": "Getting Started with Apps for the Chrome Web Store",
                    "subtitle": "Technology",
                    "description": "Arne Roomann-Kurrik"
                }
            ]
        }
    ]
}

最佳答案

需要将json数组传递给另一个activity

然后

try
    {

        JSONArray jr = jb.getJSONArray("categories");
        for(int i=0;i<jr.length();i++)
        {
            JSONObject jb1 = jr.getJSONObject(i);
            JSONArray jr1 = jb1.getJSONArray("videos");
            for(int j=0;j<jr1.length();j++)
            {
                JSONObject jb2 = jr1.getJSONObject(j);
                String title =(String) jb2.get("title");
                String thumb = (String) jb2.getString("thumb");
                Log.i(".........",title);
                Log.i(".........",thumb);

            }
        }

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

日志

02-25 02:00:38.192: I/.........(1194): 2010 Day 1 Keynote
02-25 02:00:38.192: I/.........(1194): http://www.androidbegin.com/tutorial/flag/unitedstates.png
02-25 02:00:38.202: I/.........(1194): 2010 Day 2 Keynote
02-25 02:00:38.202: I/.........(1194): http://www.androidbegin.com/tutorial/flag/russia.png
02-25 02:00:38.202: I/.........(1194): Uploading your App
02-25 02:00:38.202: I/.........(1194): http://www.androidbegin.com/tutorial/flag/russia.png
02-25 02:00:38.202: I/.........(1194): Getting Started with Apps for the Chrome Web Store
02-25 02:00:38.212: I/.........(1194): http://www.androidbegin.com/tutorial/flag/unitedstates.png

编辑;

主 Activity .java

ListView lv = (ListView) findViewById(R.id.listView1);
    ArrayList<HashMap<String,String>> arraylist= new ArrayList<HashMap<String,String>>();

          try {
                // Locate the array name in JSON
               JSONObject jb= new JSONObject("your json");
               jsonarray = jb.getJSONArray("categories");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("name", jsonobject.getString("name"));
                    map.put("thumb", jsonobject.getString("thumb"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
          String[] from = { "name","thumb" };
          int[] to = { R.id.textView1,R.id.textView2 };
          ListAdapter adapter = new SimpleAdapter(this,arraylist,R.layout.njk,from,to);
          lv.setAdapter(adapter);
          lv.setOnItemClickListener(new OnItemClickListener()
          {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                    JSONObject jb;
                    try {
                        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                        jb = jsonarray.getJSONObject(arg2);
                        intent.putExtra("key",jb.toString());
                        startActivity(intent);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }



            }
          });

第二个 Activity .java

public class SecondActivity extends Activity {

    ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        lv= (ListView) findViewById(R.id.listView1);
        ArrayList<HashMap<String,String>> arraylist= new ArrayList<HashMap<String,String>>();
        try
        {
        String value = getIntent().getStringExtra("key");

        JSONObject jb =  new JSONObject(value);
        JSONArray jr = jb.getJSONArray("videos");
        for(int j=0;j<jr.length();j++)
        {
            HashMap<String,String> map = new HashMap<String,String>(); 
            JSONObject jb2 = jr.getJSONObject(j);
            String title =(String) jb2.get("title");
            String thumb = (String) jb2.getString("thumb");
            map.put("title",title);
            map.put("thumb",thumb);
            Log.i(".........",title);
            Log.i(".........",thumb);
            arraylist.add(map);

        }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
         String[] from = { "title","thumb" };
         int[] to = { R.id.textView1,R.id.textView2 };
         ListAdapter adapter = new SimpleAdapter(this,arraylist,R.layout.njk,from,to);
         lv.setAdapter(adapter);
    }

njk.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="26dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="28dp"
        android:text="TextView" />

</RelativeLayout>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

activity_second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SecondActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

快照

enter image description here

enter image description here

关于android - 多级 JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22006448/

相关文章:

parsing - 理解阿托秒差距

ruby-on-rails - 使用 Ruby on Rails 解析 Json 数据

android - Jetpack Compose BottomSheetScaffold sheetGestures 已禁用,但当子组件可滚动时手势仍然有效

ios - 在 swift 3 中从字符串实例化 Realm 对象

javascript - 在 vue.js 中创建一个包含数据的 obj 名称

java - Spring Boot POST 参数大小限制

c# - 在 C# 窗体中访问 javascript 方法(没有 Webbrowser 或 DOM)

机器人 : How to assign default theme color to TableRow

android - 将android设备与打印机连接并打印文档

android - 从通知中启动的 Activity 按返回/主页退出应用程序