【问题标题】:JSON post to Spring ControllerJSON 发布到 Spring Controller
【发布时间】:2013-09-04 05:12:20
【问题描述】:

您好,我从 Spring 中的 Web 服务开始,所以我正在尝试在 Spring + JSON + Hibernate 中开发小型应用程序。我对 HTTP-POST 有一些问题。我创建了一个方法:

@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
    String name = test.name;
    return name;
}

我的模型测试看起来像:

public class Test implements Serializable {

private static final long serialVersionUID = -1764970284520387975L;
public String name;

public Test() {
}
}

通过 POSTMAN,我发送的只是 JSON {"name":"testName"},但总是出错;

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

我导入了 Jackson 库。我的 GET 方法工作正常。我不知道我做错了什么。我很感激任何建议。

【问题讨论】:

  • 使用POSTMAN发送请求时,是否指定header "Content-type: application/json"?
  • 好的,现在开始工作。我的问题是内容类型。还有我的第二个问题。如何在 JSON Spring 中处理实体关系?我有实体工人(当我引用类地址时)和 JSON:{“地址”:{“街道”:“asdas”,“homeNo”:“123”,“flatNo”:“123”,“邮政编码”: "123","city":"asdas"}, "name":"asd","email":"asd","pesel":"123","phone":"asd","employmentType":" asd","position":"asd","desc":"asd" } 当我尝试 POST 到 Workers 对象时,我得到了先前的错误。我做错了什么。感谢您最后的回复。
  • 您是否在标头中指定了“Accept: application/json”?

标签: java json spring spring-mvc


【解决方案1】:

使用

将您的 JSON 对象转换为 JSON 字符串

JSON.stringify({"name":"testName"})

或手动。 @RequestBody 需要 json 字符串而不是 json 对象。

注意:stringify 函数在某些 IE 版本上存在问题,firefox 可以工作

验证 POST 请求的 ajax 请求的语法。 processData:false ajax 请求中需要属性

$.ajax({ 
    url:urlName,
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser  
     processData:false, //To avoid making query String instead of JSON
     success: function(resposeJsonObject){
        // Success Action
    }
});

控制器

@RequestMapping(value = urlPattern , method = RequestMethod.POST)

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {

    //do business logic
    return test;
}

@RequestBody - 将 Json 对象隐藏到 java

@ResponseBody - 将 Java 对象转换为 json

【讨论】:

  • 如何将 JSON 数组对象 ([{a: 1}, {a: 2}]) 转换为 java?
  • @RequestBody 不会直接接受 List/Array,因为您需要创建一个包装类并将列表设置为它。
  • 你的对象结构看起来像这个类 Test{ Integer id;列表 个人列表; //getter 和 setter } JSON: {id:1,personList:[{a: 1}, {a: 2}]}
  • 我已经有一个类并且有一个带有@RequestMapping(value = urlPattern , method = RequestMethod.POST) 注释的方法。一件事,我不明白为什么我们在这里给Integer id。我还有一个疑问,setter 和 getter 是否需要数组对象中的所有属性?这是第一个数组元素 {a: 1} 可以是任何 {c: 1, g: 5} 像这样。我不知道从前端传递的完美结构。这种情况下可以写getter和setter方法吗?
  • 啊哈,我错过了@RequestBody!感谢您的帖子,帮助了我!
【解决方案2】:

您需要为模型Test类中定义的所有字段包含getter和setter --

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

【讨论】:

    【解决方案3】:

    尝试改用 application/*。并使用 JSON.maybeJson() 检查控制器中的数据结构。

    【讨论】:

      【解决方案4】:

      如果您想使用 json 作为 http 请求和响应,请执行以下操作。所以我们需要在[context].xml中进行修改

      <!-- Configure to plugin JSON as request and response in method handler -->
      <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
          <beans:property name="messageConverters">
              <beans:list>
                  <beans:ref bean="jsonMessageConverter"/>
              </beans:list>
          </beans:property>
      </beans:bean>
      <!-- Configure bean to convert JSON to POJO and vice versa -->
      <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      </beans:bean>   
      

      MappingJackson2HttpMessageConverter 到 RequestMappingHandlerAdapter messageConverters 以便 Jackson API 启动并将 JSON 转换为 Java Bean,反之亦然。通过这种配置,我们将在请求正文中使用 JSON,我们将在响应中接收 JSON 数据。

      我还为控制器部分提供了小代码sn-p:

          @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)
      
          public @ResponseBody Employee getDummyEmployee() {
          logger.info("Start getDummyEmployee");
          Employee emp = new Employee();
          emp.setId(9999);
          emp.setName("Dummy");
          emp.setCreatedDate(new Date());
          empData.put(9999, emp);
          return emp;
      }
      

      所以在上面的代码中 emp 对象将直接转换为 json 作为响应。帖子也会发生同样的情况。

      【讨论】:

        【解决方案5】:

        here

        映射请求的可消耗媒体类型,缩小主映射。

        生产者用于缩小主映射,您发送请求应指定确切的标头以匹配它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-05
          • 1970-01-01
          相关资源
          最近更新 更多