Why do I change the order of the JSON with JAXB?

0

I am developing an API Rest with Jersey and I am using JAXB and with the annotation @XmlRootElement

@XmlRootElement
public class Car {
	private int idCar;
	private String model;
	private String color;
	
	public Car() {
		
	}
	
	public Car(String model, String color) {
		setModel(model);
		setColor(color);
	}
	
	public void setIdCar(int idCar) {
		this.idCar = idCar;
	}
	
	public int getIdCar() {
		return idCar;
	}
	
	public void setModel(String model) {
		this.model = model;
	}
	
	public String getModel() {
		return model;
	}
	
	public void setColor(String color) {
		this.color = color;
	}
	
	public String getColor() {
		return color;
	}
	
	@Override
	public String toString() {
		return "Car [model=" + model + ", color=" + color + "]";
	}
	
}

I am converting a Car Class to JSON with Jersey to return it when requesting the resource

@GET
	@Path("/{num : \d+}")//digit only
	@Produces(MediaType.APPLICATION_JSON)
	public Car getCar(@PathParam("num") int id) {
		Car objCar = ConnectionDB.getCarDB(id);
		return objCar;
	}

But when doing the Get Me change the JSON Order How does jaxb mapping work to make it look like this?

    
asked by Clio 08.11.2018 в 22:50
source

1 answer

0

The simple answer is because you are using the default scheme.

As you can see in this architectural diagram

for both serialization and de-serialization, a schema is used, and as you may have observed in JAXB, two default schemas are used:

<xml ... xmlns:jxb="http://java.sun.com/xml/ns/jaxb" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" ...>

Details about the XML base schema can be found at link

and JAXB's at link .

From Java 6 the JAXB specification provides by default the properties without order .

However, you can specify the order you want by entering

@XmlType (propOrder={"idCar","model","color"})

level-leveling.

If you are using the implementation of the JAXB specification called "Eclipselink Moxy" you can add the annotation at the class level:

@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)

to ensure that properties are always printed in alphabetical order when serialized.

It is important to note that in recent versions of Java (I believe since the 11th), JAXB is no longer part of Java SE and the best thing to do is to load JAXB as a dependency for the sake of portability.

    
answered by 17.12.2018 / 21:09
source