Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey JSON key/value order

Tags:

java

json

jersey

I'm building a Java REST Web App with use of Jersey to get JSON data output.

I ran into a problem with ordering of the key/value pairs. I want it to be this order: id, name, areaId But in my JSON ouput it is this order: areaId, id, name though.

Does someone know how to control the ordering?


This is my Room Object Class:

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class RoomEntitiy {

private int id;
private String name;
private int areaId;

public RoomEntitiy() {}

public RoomEntitiy(int id, String name, int areaId) {
    this.id = id;
    this.name = name;
    this.areaId = areaId;
}
@XmlAttribute
public final int getId() {
    return id;
}

public final void setId(int id) {
    this.id = id;
}

public final String getName() {
    return name;
}

public final void setName(String name) {
    this.name = name;
}


public final int getArea() {
    return areaId;
}

public final void setArea(int areaId) {
    this.areaId = areaId;
}

}

This is my JSON output:

{
"rooms": [
    {
        "areaId": 2,
        "id": 1,
        "name": "room 831"
    },
    {
        "areaId": 1,
        "id": 2,
        "name": "room 683"
    },
    {
        "areaId": 1,
        "id": 3,
        "name": "Raum 485"
    },
    {
        "areaId": 5,
        "id": 4,
        "name": "room 600"
    },
    {
        "areaId": 2,
        "id": 5,
        "name": "room 283"
    },
    {
        "areaId": 4,
        "id": 6,
        "name": "room 696"
    }
  ]
}

UPDATE Ok, I solved it. Thanks for your replies.

I just added the following code below @XmlRootElement

@XmlType(propOrder = {
    "id",
    "name",
    "areaId"
})
like image 385
imwill Avatar asked Jul 13 '11 13:07

imwill


2 Answers

It seems that the order of the element is Alphabetical.(Yes, I am Sherlock Holmes..). In most cases there is no need to order individual attributes. But I believe I had once done some customization and you can use the following annotation to control serialization.

@XmlRootElement
@XmlType(propOrder={"id", "areaId", "name"})

If this does not work, then you could use other serialization mechanism like Jackson or Gson.

like image 189
uncaught_exceptions Avatar answered Sep 20 '22 19:09

uncaught_exceptions


JSON objects are explicitly unordered.

An object is an unordered collection of zero or more name/value pairs

If you want order, use an array (but in this case, whatever you use to process the data should just request the keys in the order it wants instead of looping).

like image 24
Quentin Avatar answered Sep 18 '22 19:09

Quentin