1.定义一个java实体类
该实体类对应json数据中需要获取的json对象
public class ParamterEntity {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.通过url获取json对象,并转化成java对象,返回java对象List
public class Test1 {
//获取具体的url,解析json对象数据
public List<ParamterEntity> getSpecificUrl(String url) {
List<ParamterEntity> paramaters = new ArrayList<ParamterEntity>();
try {
StringBuilder json = new StringBuilder();
//连接url
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)uc;
//伪造浏览器请求
httpURLConnection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
httpURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0");
//读取该url返回的json数据
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
//关闭输入流
in.close();
//将json数据转换成java数据处理
JSONObject jsonObjects = JSONObject.fromObject(json.toString());//java 转json
JSONArray jsonArray = jsonObjects.getJSONArray("rows");//其中"rows"为该json对象中的一个数组,该数组也包含了一组对象
//遍历该json对象数组
for(int j=0;j<jsonArray.size();j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
//json对象转换成ParamterEntity java对象,其中的属性需要一致
ParamterEntity param = (ParamterEntity) JSONObject.toBean(jsonObject,ParamterEntity.class);
paramaters.add(param);
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
return paramaters;
}
}