How to create JSON for JAXBElement?

1.2k views Asked by At

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 will accept {"firstName":"Alfred","lastName":"Bell"} but not {"person":{"firstName":"Alfred","lastName":"Bell"}}.

Because of that I have the following problem.

PROBLEM:

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.
   }     
}

How do I format the JSON so that JAXBElement<Car> jaxbCar recognizes it? The car must have four tires and an airbag.

DETAILS:

I am using Jersey (Java REST-API).

1

There are 1 answers

2
abdellah7000 On

Try to send your object as argument to the addPerson() method

public Person  addPerson(Person person){

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

And don't forget the add @XmlAccessorType(XmlAccessType.FIELD) right before @XmlrootElement