当前位置:  开发笔记 > 编程语言 > 正文

JAXB - 从url解组

如何解决《JAXB-从url解组》经验,为你挑选了0个好方法。

我正在尝试从这个网站显示游戏的标题和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 games;

    public List getGames() {
        return games;
    }

    public void setGames(List 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 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"%>


    
        Name: ${customer.gameTitle}
Id: ${customer.id}

但我的代码不起作用.有人可能知道我做错了什么?因为我得到了:

Name:
Id: 

仅此而已.

推荐阅读
女女的家_747
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有