2015-12-14 2 views
3

Я tryting, чтобы отобразить название и идентификатор игры с этого сайта: http://thegamesdb.net/api/GetGame.php?id=2JAXB - демаршаллизации из URL

Когда я немаршалинг из этого URL: http://www.w3schools.com/xml/note.xml все это было хорошо, но здесь был только один объект, а не список. Так что теперь у меня проблемы. Я читал некоторые учебники и примеры из Google, и я сделал этот код:

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: 

И ничего более.

+0

Какие учебники вы использовали? Мне нужно сделать то же самое, но с весенним ботинком. – Jesse

ответ

0

Единственное, что не так с вашей аннотации

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

403 = Forbidden

Solution (сделать сервер верю, что вы браузер)

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, close stre ams и проверка на NullPointer выше этого примера и до пользователя.

+0

Почему вы используете «game = games.get (0);»? Я выполнил ваши шаги, но мой второй дочерний элемент пуст/null. –

+1

game = games.get (0); из кода OP, это для извлечения первого узла . –

+0

Когда я пытаюсь распечатать список из «JAXBExample.java:», я получаю [first_value, blank]. Если я скопировал точный код в мой основной класс. Я получаю [first_value, Second_value] –

Смежные вопросы