调用NBA赛事API,完成对返回json数据的解析
程序员文章站
2022-03-26 21:47:34
...
这篇博客主要记录申请API,解析API返回的json数据,然后将需要的数据呈现到网页上。
一、申请聚合数据提供的NBA赛事的API。
二、创建自己的类,并复制API提供的接口方法。
package com.example.demo.match;
import com.example.demo.matchBean.ListObject;
import com.example.demo.teammatchBean.TeamListObject;
import com.example.demo.teammatchBean.TeamListObject2;
import net.sf.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class APItest {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//配置您申请的KEY
public static final String APPKEY ="0dfc5ed27e20ed3b98f029ff9751a34c";
//1.NBA常规赛赛程赛果
public static List<ListObject> getRequest1(){
String result =null;
String url ="http://op.juhe.cn/onebox/basketball/nba";//请求接口地址
Map params = new HashMap();//请求参数
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
params.put("dtype","");//返回数据的格式,xml或json,默认json
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
// System.out.println(object.get("result"));
return (new ResolveJson()).resolve1(result);
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//2.球队赛程赛事查询
public static List<TeamListObject2> getRequest2(String teamname){
String result =null;
String url ="http://op.juhe.cn/onebox/basketball/team";//请求接口地址
Map params = new HashMap();//请求参数
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
params.put("dtype","");//返回数据的格式,xml或json,默认json
params.put("team",teamname);//球队名称
System.out.println(teamname);
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
return (new ResolveJson()).resolve2(result);
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//3.球队对战赛赛程查询
public static List<TeamListObject2> getRequest3(String teamname1,String teamname2){
String result =null;
String url ="http://op.juhe.cn/onebox/basketball/combat";//请求接口地址
Map params = new HashMap();//请求参数
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
params.put("dtype","");//返回数据的格式,xml或json,默认json
params.put("hteam",teamname1);//主队球队名称
params.put("vteam",teamname2);//客队球队名称
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
return (new ResolveJson()).resolve2(result);
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
getRequest1();
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
public static String net(String strUrl, Map params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
strUrl = strUrl+"?"+urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
// TODO: handle exception
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
//将map型转为请求参数型
public static String urlencode(Map<String,Object>data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
因为需要,我已经对原来的代码进行了稍微的改动,需要原有的可以看聚合数据提供的示例代码。
链接:点击打开链接
三、根据三个方法返回的json数据,对其进行解析,解析成java对象。
getRequest()方法返回json对应的对象
package com.example.demo.matchBean;
import java.util.List;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:32 2018-04-24
*/
public class ListObject{
public String title;
public List<LiveObject> live;
public List<LivelinkObject> livelink;
public List<TrObject> tr;
public List<LivelinkObject> bottomlink;
public ListObject(String title, List<TrObject> tr) {
this.title = title;
this.tr = tr;
}
public ListObject(String title, List<LiveObject> live, List<LivelinkObject> livelink, List<TrObject> tr, List<LivelinkObject> bottomlink) {
this.title = title;
this.live = live;
this.livelink = livelink;
this.tr = tr;
this.bottomlink = bottomlink;
}
}
package com.example.demo.matchBean;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:33 2018-04-24
*/
public class LivelinkObject{
public String text;
public String url;
}
package com.example.demo.matchBean;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:34 2018-04-24
*/
public class LiveObject{
public String title;
public String player1;
public String player2;
public String player1info;
public String player2info;
public String player1logobig;
public String player2logobig;
public String player1url;
public String player2url;
public String player1location;
public String player2location;
public String status;
public String score;
public String liveurl;
public LiveObject(String title, String player1, String player2, String player1info, String player2info, String player1logobig, String player2logobig, String player1url, String player2url, String player1location, String player2location, String status, String score, String liveurl) {
this.title = title;
this.player1 = player1;
this.player2 = player2;
this.player1info = player1info;
this.player2info = player2info;
this.player1logobig = player1logobig;
this.player2logobig = player2logobig;
this.player1url = player1url;
this.player2url = player2url;
this.player1location = player1location;
this.player2location = player2location;
this.status = status;
this.score = score;
this.liveurl = liveurl;
}
}
package com.example.demo.matchBean;
import java.util.List;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:34 2018-04-24
*/
public class Result{
public String title;
public Statuslist statuslist;
public List<ListObject> list;
public List<TeammatchObject> teammatch;
public Result(String title, Statuslist statuslist, List<ListObject> list, List<TeammatchObject> teammatch) {
this.title = title;
this.statuslist = statuslist;
this.list = list;
this.teammatch = teammatch;
}
}
package com.example.demo.matchBean;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:34 2018-04-24
*/
public class Statuslist{
public String st0;
public String st1;
public String st2;
public Statuslist(String st0, String st1, String st2) {
this.st0 = st0;
this.st1 = st1;
this.st2 = st2;
}
}
package com.example.demo.matchBean;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:34 2018-04-24
*/
public class TeammatchObject{
public String name;
public String url;
}
package com.example.demo.matchBean;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 22:34 2018-04-24
*/
public class TrObject{
public String time;
public String player1;
public String player2;
public String player1logo;
public String player2logo;
public String player1logobig;
public String player2logobig;
public String player1url;
public String player2url;
public String link1url;
public String m_link1url;
public String link2text;
public String link2url;
public String m_link2url;
public String status;
public String score;
public String link1text;
}
package com.example.demo.matchBean;
/**
* @AUTHOR:wanderlustLee
* @DATE:Create in 20:16 2018-04-24
*/
public class JsonString{
public String reason;
public Result result;
public String error_code;
public JsonString(String reason, Result result, String error_code) {
this.reason = reason;
this.result = result;
this.error_code = error_code;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public String getError_code() {
return error_code;
}
public void setError_code(String error_code) {
this.error_code = error_code;
}
}
四、类创建完成后就可以对json进行解析。
如果抛出了这种异常
说明没有json解析需要相关的jar包
包括:commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-lang-2.4.jar (使用过高版本也会报NestableRuntimeException)
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.1.jar
log4j.jar
下载地址 点击打开链接
由于用到了json解析工具gson,还需要导入gson的jar包,去官网下载即可。
解析类:
package com.example.demo.match;
import com.example.demo.matchBean.JsonString;
import com.example.demo.matchBean.ListObject;
import com.example.demo.teammatchBean.TeamJsonString;
import com.example.demo.teammatchBean.TeamListObject2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class ResolveJson {
public List<ListObject> resolve1(String json){
Gson gson = new Gson();
JsonString jsonString = gson.fromJson(json,JsonString.class);
System.out.println(json);
// System.out.println(jsonString.result.list.get(0).tr.get(0).player1);
List<ListObject> matchlist = jsonString.result.list;
return matchlist;
}
public List<TeamListObject2> resolve2(String json){
System.out.println(json);
TeamJsonString teamJsonString = (new Gson()).fromJson(json,TeamJsonString.class);
JsonParser parse =new JsonParser(); //创建json解析器
JsonObject json2=(JsonObject) parse.parse(json);
System.out.println("reason:"+json2.get("reason").getAsString());
System.out.println(json2.get("error_code").getAsString());
JsonObject result=json2.get("result").getAsJsonObject();
JsonArray array = result.get("list").getAsJsonArray();
List<TeamListObject2> teammatchlist = new ArrayList<>();
for(int i=0;i<array.size();i++){
JsonObject subObject=array.get(i).getAsJsonObject();
TeamListObject2 listObject2 = new TeamListObject2();
listObject2.setTime(subObject.get("time").getAsString());
listObject2.setScore(subObject.get("score").getAsString());
listObject2.setPlayer1(subObject.get("player1").getAsString());
listObject2.setPlayer2(subObject.get("player2").getAsString());
listObject2.setLink1url(subObject.get("link1url").getAsString());
listObject2.setLink2url(subObject.get("link2url").getAsString());
teammatchlist.add(listObject2);
}
return teammatchlist;
}
}
五、前端显示代码
<div class="tab-content">
<div class="tab-pane active" id="panel-3842">
<table class="table" th:if="${not #lists.isEmpty(matchlist)}">
<thead>
<tr class="success">
<th>
对阵
</th>
<th>
比赛时间
</th>
<th>
比分
</th>
<th>
比赛集锦/直播
</th>
<th>
数据统计
</th>
</tr>
</thead>
<tbody>
<span th:each="match:${matchlist}" >
<tr th:each="matchtr:${match.tr}" class="warning">
<td th:text="${matchtr.player1} + 'vs' + ${matchtr.player2}"></td>
<td th:text="${matchtr.time}"></td>
<td th:text="${matchtr.score}"></td>
<td><a th:href="${matchtr.link1url}" >集锦/直播</a></td>
<td><a th:href="${matchtr.link2url}" >数据统计</a></td>
</tr>
</span>
</tbody>
</table>
</div>
<div class="tab-pane" id="panel-110129">
<form class="form-search" action="/teammatch" method="post" id="form2" name="form2">
<input name="teamname" class="form-control" type="text" placeholder="请输入要查询的球队名称" />
<button type="submit" class="btn btn-info">查询</button>
</form>
<table class="table" th:if="${not #lists.isEmpty(teammatchList)}">
<thead>
<tr class="success">
<th>
对阵
</th>
<th>
比赛时间
</th>
<th>
比分
</th>
<th>
比赛集锦/直播
</th>
<th>
数据统计
</th>
</tr>
</thead>
<tbody>
<tr th:each="teammatch:${teammatchList}" >
<td th:text="${teammatch.player1} + 'vs' + ${teammatch.player2}"></td>
<td th:text="${teammatch.time}"></td>
<td th:text="${teammatch.score}"></td>
<td><a th:href="${teammatch.link1url}" >集锦/直播</a></td>
<td><a th:href="${teammatch.link2url}" >数据统计</a></td>
</tr>
</tbody>
</table>
</div>
<div class="tab-pane" id="panel-1101">
<form class="form-search" action="/teampk" method="post" id="form3" name="form3">
<input name="teamname1" class="form-control" type="text" placeholder="请输入要查询的球队名称" />
<input name="teamname2" class="form-control" type="text" placeholder="请输入要查询的球队名称" />
<button type="submit" class="btn btn-info">查询</button>
</form>
<table class="table" th:if="${not #lists.isEmpty(teampkList)}">
<thead>
<tr class="success">
<th>
对阵
</th>
<th>
比赛时间
</th>
<th>
比分
</th>
<th>
比赛集锦/直播
</th>
<th>
数据统计
</th>
</tr>
</thead>
<tbody>
<tr th:each="teampk:${teampkList}" >
<td th:text="${teampk.player1} + 'vs' + ${teampk.player2}"></td>
<td th:text="${teampk.time}"></td>
<td th:text="${teampk.score}"></td>
<td><a th:href="${teampk.link1url}" >集锦/直播</a></td>
<td><a th:href="${teampk.link2url}" >数据统计</a></td>
</tr>
</tbody>
</table>
</div>
</div>
效果:
上一篇: windows平台kafka 搭建和使用
下一篇: Json学习(一)传统的Json解析