开发者

Jersey JSON key/value order

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"
})


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜