Home > front end >  Spring Boot REST API won't convert JSON to object
Spring Boot REST API won't convert JSON to object

Time:05-19

I'm running into a failure, but I can't figure out why. For a simple test, I want to quickly create a RESTful API to accept a JSON and convert it to an object (POJO).

Restcontroller:

@RestController
public class RESTController {

    @Autowired
    AuthorService authorService;

    @RequestMapping(value = "/setsAuthor", headers = "Accept=application/json", method=RequestMethod.POST)
    public void addAuthor(@RequestBody Author author){
        authorService.addAuthor(author);
    }

}

Data object:

@AllArgsConstructor
@Entity
@NoArgsConstructor
public class Author {

    @Id
    private Integer id;
    private String authorName;
}

Service:

@Service
public class AuthorService {

    @Autowired
    AuthorRepository authorRepository;

    public void addAuthor(Author author) {
        try {
            authorRepository.save(author);
        } catch (IllegalAccessError e) {
            System.out.println("cant save Author: "   author   " to Respository");
        }
    }

Repository interface:

public interface AuthorRepository extends CrudRepository<Author, Integer> {
}

Post Request at

http://localhost:8080/setsAuthor

With JSON:

{
    "id": 1,
    "authorName": "SomeAuthor"
}

I also tried to wrap the Items in the JSON in a "Author" :{}

The RestController won't map my JSON to the object. It always says id = null, authorName = null when I debug the program.

What am I doing wrong? I remember it always worked this way.

CodePudding user response:

Add @Getter and @Setter to entity

@AllArgsConstructor
@Entity
@NoArgsConstructor
@Getter
@Setter
public class Author {

CodePudding user response:

You can also use

@AllArgsConstructor(onConstructor = @__(@JsonCreator))

instead of @Setter

  • Related