>백엔드 개발 >PHP 튜토리얼 >Android中的JSONObject和JSONArray解析json数据_PHP教程

Android中的JSONObject和JSONArray解析json数据_PHP教程

WBOY
WBOY원래의
2016-07-13 17:07:461244검색

今天介绍一下关于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/

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/630065.htmlTechArticle今天介绍一下关于json数据解析,我们使用Android中的JSONObject和JSONArray解析json数据,有android开发的朋友可以参考一下。 String strJson = {students:...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.