弹簧mvc以json格式输出

我对spring mvc和java很新。 我想返回一个json数据而不是字符串

@RequestMapping(value = "/ex/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
    return "{"name":"MyNode", "width":200, "height":100}";
}

实际产量:
"{"name":"MyNode", "width":200, "height":100}"

我想要的输出:
{"name":"MyNode", "width":200, "height":100}

我跟着链接,但我仍然无法获得字面json输出

@RequestMapping(value =“/ ex / foos”,method = RequestMethod.GET,产生=“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;
}

输出{“result”:false,“message”:“base64内容在 [源:N / A;行:-1,列:-1]时出现意外的字符串结尾}}


你快到了:)

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 -->
链接地址: http://www.djcxy.com/p/48479.html

上一篇: spring mvc output in json format

下一篇: POST request in Spring MVC not work after migration from 3.2 to 4.1