Skip to content
Advertisement

Is it possible to change order of attributes when toJson()?

Let’s take this example. I have a pojo class as below.

public class MyRecord{
    private String name;
    private String id;

    //constructors and getters,setters
}

when I get the toJson(new MyRecord(“MyName”,”myId”) output for above I can get.

{
  "name": "MyName",
  "id": "123" 
}

And I have inherited one as follows to add the dateTime.

public class MyRecordWithDateTime extends MyRecord{
        private String DateTime;           

        //constructors and getters,setters
}

so when I called toJson(new MyRecordWithDateTime(“2016-01-01”, “MyName”, “myId”))

The output is this

{
  "name": "MyName",
  "id": "123",
  "dateTime": "2016-01-01" 
}

but I actually need that as follows. (dateTime should come first.)

{          
  "dateTime": "2016-01-01", 
  "name": "MyName",
  "id": "123"
}

Is there anyway to do that with keeping inheritance?

Advertisement

Answer

Field/member/attributes in a JSON collection do not have an order, and as far as this JSON data structure is concerned, the “order” doesn’t matter.

The only reason I can imagine you are concerned with the order is for printing/presentation purposes. In that case I suggest you manually construct the JSON string yourself.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement