简体   繁体   中英

How to return the JSON with present as false in a REST API implemented with Spring framework?

I have the following controller:

@RestController
@RequestMapping("/cities")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @GetMapping("/{cityId}")
    public Optional<City> readCity(@PathVariable Integer cityId) {
        return cityRepository.findById(cityId);
    }
}

I once was able be return an error message in JSON format by default when giving a nonexisting cityId :

{
    "present": false
}

But when I tried to reproduce by giving a nonexisting cityId , I got the null result in the response body.

My relevant dependencies in pom.xml are:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.6.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-rest-webmvc</artifactId>
  <version>${spring.data.rest.webmvc.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-mongodb</artifactId>
  <version>2.1.3.RELEASE</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.7</version>
</dependency>

Question: I would like to reproduce the previous response as {"present": false}, which is probably the default JSON in Spring in case of no resource found, how to get that?

There are many ways to achieve it: custom HttpMessageConverters , custom JsonSerializer if using Jackson.

In your case, I would return a ResponseEntity like this:

@RestController
@RequestMapping("/cities")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @GetMapping("/{cityId}")
    public ResponseEntity<?> readCity(@PathVariable Integer cityId) {
        return cityRepository.findById(cityId)
                   .map(ResponseEntity::<Object>ok)
                   .orElse(ResponseEntity.ok(Collections.singletonMap("present", false)));
    }
}

Nevertheless, I don't like returning a response like {"present": false} .

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