I am very new for spring mvc and java. i want to return a json data instead of string
@RequestMapping(value = "/ex/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
return "{\"name\":\"MyNode\", \"width\":200, \"height\":100}";
}
actual output:
"{\"name\":\"MyNode\", \"width\":200, \"height\":100}"
output i want:
{"name":"MyNode", "width":200, "height":100}
i followed the link but i still can't get literal json output
@RequestMapping(value = "/ex/foos", method = RequestMethod.GET, produces = "application/json") @ResponseBody public JsonNode getFoosAsJsonFromREST() {
String everything = "{\"a\":2,\"b\":\"astring\",\"c\":6}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(everything);
return node;
}
output { "result": false, "message": "Unexpected end-of-String when base64 content\n at [Source: N/A; line: -1, column: -1]" }
答案 0 :(得分:0)
你快到了:)
JSON只是一种对象格式,因此您必须返回一个具有键:值对的对象。
@RequestMapping(value = "/ex/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public MyJSONRespone getFoosAsJsonFromREST() {
MyJSONRespone myResponse = new MyJSONRespone();
myResponse.setName("MyNode");
myResponse.setWidth(200);
myResponse.setHeight(100);
return myResponse;
}
class MyJSONRespone{
private String name;
private Integer width;
private Integer Height;
//setters and getters
}
如果您使用Maven,还要确保POM中具有正确的依赖关系:
<!-- Jackson/JSON START -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.2</version>
</dependency>
<!-- Jackson/JSON END -->