0

I am runing this code in my Java app and the first line throws an exception IllegalAnnotationExceptions :

JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);                         
jaxbMarshaller.marshal(productFound, serverOutput);

I'm not familiar with XML format. So, from what I've seen on the internet, the problem comes from the class Product, which means this file :

package service;

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "Product")
@XmlAccessorType(XmlAccessType.FIELD)


public class Product {

    @XmlElement(name = "id")
    private String id;
    @XmlElement(name = "name")
    private String name;
    @XmlElement(name = "price")
    private String price;


    public Product(String id, String name, String price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}

Especially regarding the annotations. Did I do something wrong ? Or does something look weird in my code ?

Thanks !

user54517
  • 2,020
  • 5
  • 30
  • 47

2 Answers2

2

Your Product class must have a no-arg constructor. For Java classes with no constructor, the Java compiler synthesises a no-arg one for the class. Once you explicitly add a constructor, no default no-arg constructor is added by the compiler, hence here you must also add an explicit no-arg constructor for the implementation of JAXB to use.

1

Depending on the JAXB implementation that you are using, you might need to add a no-argument constructor to your Product class, e.g.:

public Product() {}

See this question for further information.

user7217806
  • 2,014
  • 2
  • 10
  • 12