[英]JAXB - unmarshalling from url
我正在嘗試從這個網站顯示游戲的標題和ID: http ://thegamesdb.net/api/GetGame.php?id = 2
當我從這個網址解組時: http : //www.w3schools.com/xml/note.xml一切都好,但這里只有一個對象,而不是列表。 所以我現在遇到問題。 我正在閱讀谷歌的一些教程和示例,我制作了這段代碼:
Data.java:
@XmlRootElement( name = "Data" )
@XmlAccessorType (XmlAccessType.FIELD)
public class Data {
@XmlElement(name = "Game")
List<Game> games;
public List<Game> getGames() {
return games;
}
public void setGames(List<Game> games) {
this.games = games;
}
}
Game.java文件:
@XmlRootElement(name = "Game")
@XmlAccessorType (XmlAccessType.FIELD)
public class Game {
private int id;
private String gameTitle;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getGameTitle(){
return gameTitle;
}
public void setGameTitle(String gameTitle){
this.gameTitle = gameTitle;
}
}
控制器:
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale) throws MalformedURLException {
ModelAndView model = new ModelAndView("index");
JAXBExample test = new JAXBExample();
Game customer = test.readXML();
model.addObject("customer", customer);
return model;
}
JAXBExample.java:
public class JAXBExample {
public Game readXML() throws MalformedURLException {
Data customer = null;
Game game = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Data.class);
URL url = new URL("http://thegamesdb.net/api/GetGame.php?id=2");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
customer = (Data) jaxbUnmarshaller.unmarshal(url);
List<Game> games = customer.getGames();
game = games.get(0);
} catch (JAXBException e) {
e.printStackTrace();
}
return game;
}
}
和index.jsp:
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<tiles:insertDefinition name="defaultTemplate">
<tiles:putAttribute name="body">
Name: ${customer.gameTitle}<br />
Id: ${customer.id}<br />
</tiles:putAttribute>
</tiles:insertDefinition>
但我的代碼不起作用。 有人可能知道我做錯了什么? 因為我得到了:
Name:
Id:
僅此而已。
你的注釋唯一錯誤的是
public class Game {
private int id;
@XmlElement(name = "GameTitle") //You need to add this since first letter is uppercase, otherwise the GameTitle will not unmarshall.
private String gameTitle;
... your code ...
}
那么為什么其他工作呢?
服務器返回HTTP響應代碼:403為URL: http : //thegamesdb.net/api/GetGame.php?id = 2
解決方案 (讓服務器相信您是一個瀏覽器)
URL url = new URL("http://thegamesdb.net/api/GetGame.php?id=2");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = http.getInputStream();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
customer = (Data) jaxbUnmarshaller.unmarshal(is);
List<Game> games = customer.getGames();
game = games.get(0);
注意: Try catch final
,關閉流並檢查NullPointer
是否超出此示例並且取決於用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.