简体   繁体   中英

How can I produce a JSON_OBJECT instead of JSON_ARRAY as result to my API queries

For some time I have Struggled with this problem I have distilled a short sample to produce my results

When Spring-Boot produces api output and there is more than one record it is enclosed as a JSON_ARRAY starting with [ and ending with ] with comma-seperated JSON_OBJECTS inside

I Want the result to be surrounded by another JSON_OBJECT like {entity:[{.....},{.....}]}

eg

[
    {
        "locationId": "l1",
        "locationName": "New York"
    },
    {
        "locationId": "l3",
        "locationName": "London"
    }
]

must become

{
location:{
    [{
      "locationId": "l1",
      "locationName": "New York"
     },
     {
      "locationId": "l3",
      "locationName": "London"
     }]
}}

public class Location {
   private String id;
   private String name;
}
// Getter & Setters etc ommited

Obvously I have googled for this and have tried many solution and could not find any

If I add "org.springframework.boot:spring-boot-starter-data-rest" to my project spring will create some endpoints for my entities that actually produces the desired results, however I have some non-standars queries that is excluded and I need to do them myself

If you can teach me to overcome this difficulty I will apreciate it

Create a class as follows:

public class LocationWrapper {
    private List<Location> location;
}

and return an instance of LocationWrapper from the @RestController method.

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