首页 > 代码库 > json两层解析

json两层解析

 1 public class Demo {
 2 
 3     public static void main(String[] args) {
 4         try {
 5             // 创建连接                              服务器的连接地址
 6             URL url = new URL(
 7                     "http://apicloud.mob.com/v1/mobile/address/query?phone=13026610069&key=1b2e046d45634");
 8             try {
 9                 // 创建输入流
10                 BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
11                 // 创建一个StringBuffer对象
12                 StringBuffer sb = new StringBuffer();
13                 // 定义一个字符串变量
14                 String st ;
15                 // 不等于null的时候一直读
16                 while ((st = br.readLine()) != null) {
17                     // 读取的所有字符串添加到sb
18                     sb.append(st);
19                 }
20                 // 创建第一个解析                                  需要解析的字符串
21                 JSONObject first = JSONObject.fromObject(sb.toString());
22                 // 打印需要解析的字符串
23                 System.out.println(sb.toString());
24                 System.out.println("===============json第一层解析============");
25                 System.out.println("msg:"+first.get("msg"));
26                 System.out.println("retCode:"+first.get("retCode"));
27                 System.out.println("result:"+first.get("result"));
28                 
29                 // 创建第二个解析                                需要解析的字符串
30                 JSONObject second = JSONObject.fromObject(first.get("result"));
31                 System.out.println("==============json第二层解析==============");
32                 System.out.println("city:"+second.get("city"));
33                 System.out.println("cityCode:"+second.get("cityCode"));
34                 System.out.println("mobileNumber:"+second.get("mobileNumber"));
35                 System.out.println("operator:"+second.get("operator"));
36                 System.out.println("province:"+second.get("province"));
37                 System.out.println("zipCode:"+second.get("zipCode"));
38             } catch (IOException e) {
39                 e.printStackTrace();
40             }
41         } catch (MalformedURLException e) {
42             e.printStackTrace();
43         }
44     }
45 
46 }

 

json两层解析