Issue
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]" }
Solution
You're nearly there :)
JSON is just an object format so you must return an object with key:value pairs.
@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
}
Also make sure you have the correct dependency in your POM if you are using Maven:
<!-- 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 -->
Answered By - fillup