简体   繁体   中英

Proper order in the JSON response according to bean declaration

Is there any way for the JSON response to be formed in the same order in which I declare the attributes in the POJO?

If possible I would like to keep the POJOS as simple as possible, without annotations and things like that (like @JsonPropertyOrder, or @XmlType propOrder, ...)

If this is my POJO:

public class Header {

    private String id;
    private String date;
    private String name;

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

    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }

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

}   

I want the response to be:

{
   "header": {
      "id": "1",
      "date": "20191031223016", 
      "name": "SAMPL"
  }
}

... not this:

{
  "header": {
    "date": "20191031223016",
    "id": "1",
    "name": "SAMPL"
  }
}

JSON has by definition in it's language spec unordered keys. That means there is no differentiation between JSON objects with it's keys in different orders.

If you require ordered data, you should wrap the members into a JSON list in a structure like so:

[
    {"key": "id", "value": 1"},
    {"key" ....
]

which also isn't really the purpose of JSON. You should accept the keys in any order in any case.

In that case, according to my taste, the cleanest solution would be this:

import javax.xml.bind.annotation.XmlType;

@XmlType(propOrder = {"id", "date", "name"})
public class Header {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM