java 访问url获取数据并解析

java代码

  1. protected String getJsonString(String urlPath) throws Exception {  
  2.         URL url = new URL(urlPath);  
  3.         HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  4.         connection.connect();  
  5.         InputStream inputStream = connection.getInputStream();  
  6.         //对应的字符编码转换  
  7.         Reader reader = new InputStreamReader(inputStream, "UTF-8");  
  8.         BufferedReader bufferedReader = new BufferedReader(reader);  
  9.         String str = null;  
  10.         StringBuffer sb = new StringBuffer();  
  11.         while ((str = bufferedReader.readLine()) != null) {  
  12.             sb.append(str);  
  13.         }  
  14.         reader.close();  
  15.         connection.disconnect();  
  16.         return sb.toString();  
  17.     } 

 

xml代码

  1. {"FatherName":"Marry",  
  2.     "Childs":  
  3.     [  
  4.         {"Name":"A"},  
  5.         {"Name":"B"},  
  6.         {"Name":"C"},  
  7.     ]  
  8. }  

 

java代码

  1. public void jsonToObj(String jsonStr) throws Exception {  
  2.         Page page = new Page();  
  3.         JSONObject jsonObject = new JSONObject(jsonStr);  
  4.         String fatherName = jsonObject.getString("FatherName");  
  5.         JSONArray childs= jsonObject.getJSONArray("Childs");  
  6.         int length = childs.length();  
  7.         for (int i = 0; i < length; i++) {  
  8.             jsonObject = items.getJSONObject(i);  
  9.             String childName = jsonObject.getString("Name");  
  10.         }  
  11.     }  

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值