-1

I am generating below response using java code ( java response Object), I would like to format response , tried changing sequence of object

Expected output

{
"header": {
      "specVersion": "1.0",
      "correlationId": "2526a923-6953-4dbc-a000-778f22de339c",
      "payloadContentType": "application/json",
      "id": "241f6d36-b792-4b61-9526-9d3b6270cc3c",
      "time": "2022-08-02 11:01:51.439",
      "applicationInstanceId": "v1"
   },
   "payload": {
      "success": {
         "code": 200,
         "message": "OK",
             },
      "failure": {
         "code": 0
      },
      "fileUid": "324343-b792-4b61-9526-9d3b6270cc3c"
   },
   "fileID": "241f6d36-b792-4b61-9526-9d3b6270cc3c"
}

Current output

{
   "payload": {Sucess and failure block
                },
   "header": { header block
   },
   "fileID": "id"
}
 
John D
  • 113
  • 3
  • 5
  • 15
  • 1
    You want JSON to be in a particular order? You can't have it - JSON objects are by definition unordered. And code that expects a particular order is broken code. – access violation Aug 02 '22 at 02:33
  • There are plenty of existing answers saying the same thing. Example: https://stackoverflow.com/questions/28697119/java-json-object-insertion-order-maintenance – access violation Aug 02 '22 at 02:36
  • Does this answer your question? [Java JSON object insertion order maintenance](https://stackoverflow.com/questions/28697119/java-json-object-insertion-order-maintenance) – vanje Aug 02 '22 at 15:36

1 Answers1

0

What library do you need to serialize Java object to JSON string? If using Jackson, you can use @JsonPropertyOrder or @JsonProperty with parameter index(like @JsonProperty(index = 1)) to custom orders of fields.

Using @JsonPropertyOrder

// string array will control the order of fields
@JsonPropertyOrder({"payload", "header", "fileID"})
public class Response {
  private HeaderClass header;
  private PayloadClass payload;
  private String fileID;
}

Using @JsonProperty

public class Response {
  // index will control the order of field
  @JsonProperty(index = 2)
  private HeaderClass header;
  @JsonProperty(index = 1)
  private PayloadClass payload;
  @JsonProperty(index = 3)
  private String fileID;
}
SteveHu
  • 82
  • 9