如何为JAXBElement创建JSON?

时间:2012-10-13 19:29:26

标签: java json jersey jaxbelement

BACKGROUNG

@XmlRootElement
public class Person {
    private String firstName;
    private String lastName;

    ...//accessors
}


@Path("mypath")
 public class PersonResource{
   @POST
   @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response addPerson(JAXBElement<Person> jaxbPerson) {
      Person person = jaxbPerson.getValue();
       ...//logic etc.
   }     
}

PersonResource. addPerson将接受{"firstName":"Alfred","lastName":"Bell"}但不接受{"person":{"firstName":"Alfred","lastName":"Bell"}}

因此我有以下问题。

问题:

GIVEN

@XmlRootElement
public class car {
    private String maker;
    private String model;

   private AirBag airbag;
   private List<Tire> tires;

   @XmlElementWrapper(name = "tires")
   @XmlElement(name = "tire")
   public Set<Tire> get Tires() {
       return this.tires;
   }
    ...// more accessors
}


@Path("add-car")
 public class CarResource{
   @POST
   @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response addPerson(JAXBElement<Car> jaxbCar) {
       Car car = jaxbCar.getValue();
       ...//logic etc.
   }     
}

如何格式化JSON以便JAXBElement<Car> jaxbCar识别它?汽车必须有四个轮胎和一个安全气囊。

详情:

我正在使用Jersey(Java REST-API)。

1 个答案:

答案 0 :(得分:0)

尝试将您的对象作为参数发送到addPerson()方法

public Person  addPerson(Person person){

    Person fme = new Person ();
        ...
}

不要忘记在@XmlAccessorType(XmlAccessType.FIELD)

之前添加@XmlrootElement