Adnroid解析Json数组DEMO实例
在线生成JAVA实体类工具
需要用到的Json解析库Gson请自行解决
下面我们来看下具体用法
1、使用Android中的JSONObject和JSONArray解析json数据
01 | String strJson = "{\"UrlName\":[{\"name\":\"jsons.cn\",\"age\":2}, {\"name\":\"Json工具\",\"age\":2}]}" ; |
03 | JSONObject jo = new JSONObject(strJson); |
04 | JSONArray jsonArray = (JSONArray) jo.get( "UrlName" ); |
05 | for ( int i = 0 ; i < jsonArray.length(); i) { |
06 | JSONObject o = (JSONObject) jsonArray.get(i); |
07 | System.out.println( "name:" o.getString( "name" ) "," "age:" |
10 | } catch (JSONException e) { |
2、使用Gson中的JsonReader解析json数据
02 | String string = "{\"Root\":1, \"UrlName\":[{\"name\":\"Jsons.cn\", \"age\":2},{\"name\":\"Json解析\", \"age\":2}]}" ; |
03 | StringReader sr = new StringReader(string); |
04 | JsonReader jr = new JsonReader(sr); |
06 | if (jr.nextName().equals( "Root" )) { |
07 | System.out.println( "最高级别: " jr.nextString()); |
08 | if (jr.nextName().equals( "UrlName" )) { |
10 | while (jr.hasNext()) { |
12 | if (jr.nextName().equals( "name" )) |
13 | System.out.print( "姓名:" jr.nextString()); |
14 | if (jr.nextName().equals( "age" )) { |
15 | System.out.println( " , 年龄:" jr.nextInt()); |
23 | } catch (FileNotFoundException e) { |
原文链接:Adnroid解析Json数组实例