java直接访问链接url,并对返回的json字符串进行解析

一,java访问url,并返回json 字符串

//parm:请求的url链接  返回的是json字符串
	public static String getURLContent(String urlStr) {               
	       
		//请求的url 
	    URL url = null;      
	    
	    //建立的http链接  
	    HttpURLConnection httpConn = null;  
	    
	    //请求的输入流
	    BufferedReader in = null;   
	    
	    //输入流的缓冲
	    StringBuffer sb = new StringBuffer(); 
	    
	    try{     
		     url = new URL(urlStr);     
		     
		     in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") ); 
		     
		     String str = null;  
		    
		     //一行一行进行读入
		     while((str = in.readLine()) != null) {    
		        sb.append( str );     
	         }     
        } catch (Exception ex) {   
	            
        } finally{    
	         try{             
		          if(in!=null) {  
		           in.close(); //关闭流    
	              }     
            }catch(IOException ex) {      
	        
            }     
        }     
        String result =sb.toString();     
        return result;    
    }  

二.对返回的json字符尽心解析,使用到的jar包



//将json字符串转换为json对象,进行解析
	public static void main(String[] args){
		
		//假设返回的json字符串为 strJson
		String strJson = "[{id:'001',name:'张三',age:'32'},{id:'002',name:'张四',age:'11'},{id:'003',name:'张五',age:'20'}]" ;
		
//		String strJson = getURLContent("https://www.wikidata.org/w/api.php?action=wbsearchentities&search=Fudan&language=en&limit=20&format=json") ;
		
		strJson="[" + strJson + "]" ;
		
		System.out.println(strJson) ;
		
		//将字符串转换为JSONArray对象
		try{
			JSONArray jsonArray = JSONArray.fromObject(strJson) ;
			
			if(jsonArray.size() > 0 ){
				//遍历jsonArray数组,把每个对象转成json对象
				for(int i = 0 ;i < jsonArray.size() ;i ++){
					
					JSONObject jsonObject = jsonArray.getJSONObject(i) ;
					     
					    //如果jsonOjbect中还包含jsonObject的话,就继续使用方法 getJSONObject(key) 返回下一层的json对象
//						JSONObject sub_jsonObject = jsonObject.getJSONObject("searchinfo") ;
						
					System.out.println(jsonObject.get("search")) ;
						
				}
			}
			
			
		}catch(Exception e){
			
		}
		
	}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值