Paul
Paul

Reputation: 63

Spring return json

I have a Spring RestController which I am starting in locahost:8080. When I send a request to it (localhost:8080/people) I get a response in XML format. How can I make it JSON? When I send the request using Opera web browser I get XML format, but when I use the terminal( I use Mac) the answer to the request is Json. How can I make the answer in the browser be a JSON format.

Controller

package People;

import java.util.List;
import java.util.stream.Collectors;


import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import org.springframework.web.bind.annotation.*;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
@RequestMapping("people")
public class PersonController {

    private final PersonRepository repository;

    PersonController(PersonRepository repository){
        this.repository = repository;
    }

    @GetMapping
    public Resources<Resource<Person>> all(){
        List<Resource<Person>> persons = repository.findAll().stream()
                .map(employee -> new Resource<>(employee,
                        linkTo(methodOn(PersonController.class).one(employee.getId())).withSelfRel(),
                        linkTo(methodOn(PersonController.class).all()).withRel("Persons")))
                .collect(Collectors.toList());

        return new Resources<>(persons,
                linkTo(methodOn(PersonController.class).all()).withSelfRel());
    }

    @PostMapping("")
    public Person newEmployee(@RequestBody Person newEmployee) {
        return repository.save(newEmployee);
    }

    @GetMapping("{id}")
    public Resource<Person> one(@PathVariable Long id) {
        Person Person = repository.findById(id)
                .orElseThrow(() -> new PersonNotFoundException(id));

        return new Resource<>(Person,
                linkTo(methodOn(PersonController.class).one(id)).withSelfRel(),
                linkTo(methodOn(PersonController.class).all()).withRel("Persons"));
    }

    @PutMapping("{id}")
    public Person replacePerson(@RequestBody Person newPerson,@PathVariable Long id){
        return repository.findById(id)
                .map(Person -> {
                    Person.setName(newPerson.getName());
                    Person.setLastName(newPerson.getLastName());
                    return repository.save(Person);
                }).orElseGet(() -> {
                    newPerson.setId(id);
                    return repository.save(newPerson);
                });
    }

    @DeleteMapping("{id}")
    void deletePerson(@PathVariable Long id) {
        repository.deleteById(id);
    }

}

This is how the response looks like

<html>
<body>
<h1>Whitelabel Error Page</h1>
<p>
This application has no explicit mapping for /error, so you are seeing this as a fallback.
</p>
<div id="created">Mon Oct 29 22:41:51 MSK 2018</div>
<div>
There was an unexpected error (type=Internal Server Error, status=500).
</div>
<div>
Could not marshal [Resources { content: [Resource { content: Person(id=1, Name=Paul, LastName=Walker), links: [<http://localhost:8080/people/1>;rel="self", <http://localhost:8080/people>;rel="Persons"] }, Resource { content: Person(id=2, Name=Stan, LastName=Smith), links: [<http://localhost:8080/people/2>;rel="self", <http://localhost:8080/people>;rel="Persons"] }], links: [<http://localhost:8080/people>;rel="self"] }]: null; nested exception is javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.internal.SAXException2: unable to marshal type "org.springframework.hateoas.Resource" as an element because it is not known to this context.]
</div>
</body>
</html>

Console log

2018-10-29 23:57:26.747  INFO 21281 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-10-29 23:57:26.747  INFO 21281 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-10-29 23:57:26.767  INFO 21281 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms
2018-10-29 23:57:26.985  WARN 21281 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not marshal [Resource { content: Person(id=1, Name=Paul, LastName=Walker), links: [<http://localhost:8080/people/1>;rel="self", <http://localhost:8080/people>;rel="Persons"] }]: null; nested exception is javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: class People.Person nor any of its super class is known to this context.
javax.xml.bind.JAXBException: class People.Person nor any of its super class is known to this context.]]

Upvotes: 2

Views: 412

Answers (1)

Vasif
Vasif

Reputation: 798

Please try to add producer to your get method as below

 @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)

Upvotes: 2

Related Questions