Java – malformed JSON: unexpected ‘<' in spring
•
Java
I want to make JSON from JPA @ entity. I have
@Entity @JsonAutoDetect public class Bar implements Serializable { @Id @GeneratedValue private Integer id; private String title; //omitting other stuff }
My controller is
@RestController public class BarController { @Autowired private BarService barService; @RequestMapping(value = "/",method = RequestMethod.GET,headers = "Accept=application/json",produces={"application/json"}) public List<Bar> list() { return barService.findAllBars()); } }
I encountered this error in my browser
And at the postman
What's the problem
Solution
I found a fatal error and you got bar barservice The list of findallbars (), you may need to convert the list into JSON and add the method as
public static String toJSON(Object object) { if ( object == null ){ return "{}"; } try { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return "{}"; }
Now change to
@RequestMapping(value = "/",produces={"application/json"}) public String list() { return toJSON(barService.findAllBars()); }
I hope this works. If you have any questions, feel free to query in the comment session
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码