I have a problem with returning an object in json format. This is my function to return a json object:
@GetMapping("/api/code/{n}")
@ResponseBody
public Code getCodeJson(@PathVariable int n) {
Code code = codeList.get(n - 1);
return code;
}
Objects of type Code are stored in a list, and I want to access them by the path variable n. The return looks like this:
{"id":1,"code":"{\"code\":\"hello world\"}","dateTime":"2021-10-05T16:49:31.911591"}
I don't know why this is happening, it should return a json that looks like this:
{"id":1,"code":"hello world","dateTime":"2021-10-05T16:49:31.911591"}
This is how I add code objects to the codeList
@PostMapping("/api/code/new")
@ResponseBody
public String addNewCode(@RequestBody String code) {
Code newCode = new Code(code);
codeList.add(newCode);
return "{\n" + "\"id\" : \"" + newCode.getId() + "\"\n}";
}
This is Code.java class
public class Code {
private static int currentId = 1;
private int id;
private String code;
private LocalDateTime dateTime;
public Code(String code) {
this.id = currentId;
this.code = code;
this.dateTime = LocalDateTime.now();
currentId++;
}
public int getId() {
return id;
}
public String getCode() {
return code;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setCode(String code) {
this.code = code;
this.dateTime = LocalDateTime.now();
}
}