Alex Dowining
Alex Dowining

Reputation: 970

Binding XML with JAXB annotations

I have the following XML format:

 <repositories>
     <set>
       <id>1</id>
       <name>First</name>
       <spec>data</spec>
     </set>
    <set>
       <id>2</id>
       <name>INFO</name>
       <spec>main</spec>
    </set>
      .
      .
 </repositories>

I create the following package-info.java

 @javax.xml.bind.annotation.XmlSchema (
 elementFormDefault=XmlNsForm.QUALIFIED,
 xmlns = {}
 )

package website.model;

import javax.xml.bind.annotation.XmlNsForm;

ANd the following classes:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Repositories {

@XmlElement
private ListofRepositories repositories;

public ListofRepositories getRepositories() {
    return repositories;
}

public void setRepositories(ListofRepositories repositories) {
    this.repositories = repositories;
}

}

Wrap the sets

@XmlAccessorType(XmlAccessType.FIELD)
public class ListofRepositories {

private List<Sets> set;

public List<Sets> getSet() {
    return set;
}

public void setSet(List<Sets> set) {
    this.set = set;
}

}

And the data:

@XmlAccessorType(XmlAccessType.FIELD)
public class Sets {

private Long id;
private String name;
private String spec;

//get set

}

I don't know why this doesn't work. The response is always null. I implemented similar processes with Java and JAXB annotations and i never had this kind of problem. Does anyone knows what is wrong and how can i fix it?

Upvotes: 1

Views: 307

Answers (2)

Priyank Doshi
Priyank Doshi

Reputation: 13161

For the above xml, you need following class structure:

@XmlRootElement(name="repositories")
@XmlAccessorType(XmlAccessType.FIELD)
public class Repositories {

@XmlElement
private List<Sets> set;

//getter and setter

}

@XmlAccessorType(XmlAccessType.FIELD)
public class Sets {

private Long id;
private String name;
private String spec;

//getter and setter

}

But, according to your class structure you will get following xml:

<Repositories>
  <repositories>
    <set>
      <id></id>
      <name></name>
      <spec></spec>
    </set>
    <set>
      <id></id>
      <name></name>
      <spec></spec>
    </set>
    .
    .
    .
  </repositories>
</Repositories>

Upvotes: 2

Zolt&#225;n Haindrich
Zolt&#225;n Haindrich

Reputation: 1808

with JAXB you could also generate these classes from an xsd file -- and check the incoming xml against the xsd (which will show why it will not accept it)

Upvotes: 1

Related Questions