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();
}
}
CodePudding user response:
You can update the addNewCode to accept Code
or new DTO CodeDto
as the request body instead and use that instead. As of now you are getting the entire request body as string and assigning it to the code causing the current response.
@PostMapping("/api/code/new")
@ResponseBody
public String addNewCode(@RequestBody CodeDto code) {
Code newCode = new Code(code.getCode());
codeList.add(newCode);
return "{\n" "\"id\" : \"" newCode.getId() "\"\n}";
}
As you are passing {"code":"hello world"}
as request body the above code will automatically deserialize it properly into an instance of CodeDto
object with code attribute set to "hello world".
public class CodeDto {
private String code;
public CodeDto(String code) {
this.code = code;
}
public CodeDto() {}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}