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 // 讀取的所有字串添加到sb18 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 }