一,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){
}
}