im new in spring boot i want add post to category but i a get this error
"message": "JSON parse error: Cannot construct instance of com.global.api.model.Category (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (‘food’)",
"path": "/api/posts"
}
this is category entity
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Category {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
}
this is post entity
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Post {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String description;
private LocalDateTime createdAt;
@ManyToOne
private Category category;
@ManyToOne
private User user;
this is post service and service implement
@Override
public Post createPost(CreatePostRequest post, Category category, String jwt) throws Exception {
User user = userService.findUserByJwtToken(jwt);
Post newPost = new Post();
newPost.setTitle(post.getTitle());
newPost.setDescription(post.getDescription());
newPost.setCreatedAt(LocalDateTime.now());
newPost.setCategory(category);
newPost.setUser(user);
return postRepository.save(newPost);
}
post service
public Post createPost(CreatePostRequest request, Category category, String jwt) throws Exception;
can any one help tell me where the problem when i create new post
{
"title":"Second post with post response class message and post object",
"description": "you can test the api here!",
"category":"food"
}
>Solution :
you have a Category object inside Post class, But in the post request you are sending a category String of "food" which is wrong. the right JSON would be
{ "title":"Second post with post response class message and post object",
"description": "you can test the api here!",
"category": {"name":"food"}
}
this will solve the deserializer issue.
you may run into another issue with detached object as Category is new object to database that has no Id, adding @ManyToOne(cascade = CascadeType.ALL) will fix it for now, but I advise you to search about ManyToOne to find the best solution for you case