Home > php教程 > php手册 > Android中的JSONObject和JSONArray解析json数据

Android中的JSONObject和JSONArray解析json数据

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 10:10:05
Original
1375 people have browsed it

今天介绍一下关于json数据解析,我们使用Android中的JSONObject和JSONArray解析json数据,有android开发的朋友可以参考一下。

       String strJson = "{"students":[{"name":"Jack","age":12}, {"name":"Vista","age":23}, {"name":"Kaka","age":22}, {"name":"Hony","age":31}]}";
        try {
            JSONObject jo = new JSONObject(strJson);
            JSONArray jsonArray = (JSONArray) jo.get("students");
            for (int i = 0; i                 JSONObject o = (JSONObject) jsonArray.get(i);
                System.out.println("name:" + o.getString("name") + "," + "age:"
                        + o.getInt("age"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

 

2.使用gson中的JsonReader解析json数据

try {
            String string = "{"class":1, "students":[{"name":"jack", "age":21},{"name":"kaka", "age":21},{"name":"lucy", "age":21}]}";
            StringReader sr = new StringReader(string);
            JsonReader jr = new JsonReader(sr);
            jr.beginObject();
            if (jr.nextName().contains("class")) {
                System.out.println("班级: " + jr.nextString());
                if (jr.nextName().equals("students")) {
                    jr.beginArray();
                    while (jr.hasNext()) {
                        jr.beginObject();
                        if (jr.nextName().equals("name"))
                            System.out.print("姓名:" + jr.nextString());
                        if (jr.nextName().equals("age")) {
                            System.out.println(" , 年龄:" + jr.nextInt());
                        }
                        jr.endObject();
                    }
                    jr.endArray();
                }
            }
            jr.endObject();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


Json解析库gson: http://code.google.com/p/google-gson/

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
android studio
From 1970-01-01 08:00:00
0
0
0
Android webview interacts with remote page?
From 1970-01-01 08:00:00
0
0
0
java - Android calls c++lib
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template