Return Object JSON in Java

3

I have a layer repository in my application Java that has a method to return all the authors:

public Stream<Author> getAllAuthors() {
    return StreamSupport.stream(authorRepository.findAll().spliterator(), true);  
}

And I have another layer controller that works as Endpoint that calls this method to see all the authors through the URL :

 @ResponseStatus(HttpStatus.OK) 
 @RequestMapping(value = "/authors", method = RequestMethod.GET, produces =  MediaType.APPLICATION_JSON_VALUE) 
 public Stream<Author> sampleExampleGet() throws IOException {
     return this.authorsManager.getAllAuthors(); 
 }

I need to return a JSON object with the authors, but the answer I get is the following:

{
  "parallel": true
}

I have imported the following dependencies to transform objects to JSON

<dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
</dependency>

The problem that in Endpoint I do not know how to return a JSON .

    
asked by charli 27.07.2018 в 17:08
source

1 answer

3

My advice is to transform the Stream to a List:

@ResponseStatus(HttpStatus.OK) 
@RequestMapping(value = "/authors", method = RequestMethod.GET,
    produces =  MediaType.APPLICATION_JSON_VALUE) 
public List<Author> sampleExampleGet() throws IOException {
     return this.authorsManager.getAllAuthors().collect(Collectors.toList()); 
}

In fact, I would modify the method (of the Service?) so that it does not create the Stream:

public List<Author> getAllAuthors() {
    return authorRepository.findAll();
}

And it would directly return that result.

    
answered by 27.07.2018 / 17:16
source