【问题标题】:Do we have to have to post json object with exactly same fields as in pojo object in controller?我们是否必须在控制器中发布具有与 pojo 对象完全相同的字段的 json 对象?
【发布时间】:2015-03-27 18:24:55
【问题描述】:

我是 spring rest 的新手,在将 JSON 对象从 jquery 映射到控制器时遇到问题。我的 jquery JSON 对象缺少一些字段,这些字段存在于控制器上的 java 对象中。我是否必须创建新类来映射此类对象,或者有什么方法可以在不创建新类的情况下映射这些对象?

这里是代码

控制器:

@RequestMapping(value = "/createTest", method = RequestMethod.POST,consumes="application/json")
    @ResponseBody
    public String createTest(@RequestBody TestJsonDTO testJson)
            throws JsonProcessingException, IOException {
//....

TestJsonDTO:

 public class TestJsonDTO {

 private TestSet testSet;

 private List<MainQuestion> questionsInTest;

 //gettters and setters

测试集:

public class TestSet implements Serializable {

public TestSet() {
}

@Id
@GeneratedValue
private int id;
private String name;
private int fullmark;
private int passmark;
String duration;
Date createDate = new Date();
Date testDate;
boolean isNegativeMarking;
boolean negativeMarkingValue;

主要问题:

public class MainQuestion implements Serializable {

private static final long serialVersionUID = 1L;
public MainQuestion() {

}
@Id
@GeneratedValue
private int id;
private String name;

还有我的 jquery post 方法

function createTest() {
    $.ajax({
        type : 'POST',
        url : "http://localhost:8085/annotationBased/admin/createTest",
        dataType : "json",
        contentType : "application/json",
        data : testToJSON(),
        success : function() {
            alert("success")
        },
        error : function(msg) {
            alert("error while saving test");
        }
    });

}

function testToJSON() {
    listOfQuestionForTest = questionToAdd;//array of ids of questions
    return JSON.stringify({
        "testSet.name" : $('#testname').val(),
        "testSet.fullmark" : parseInt($('#fullmark').val()),
        "testSet.passmark" : parseInt($('#passmark').val()),
        "questionsInTest" : listOfQuestionForTest
    // "testDate":$('#testDate').value()
    })

}

JSON.stringify 中,我不会发送TestJsonDto 中的所有字段。我怎样才能映射这个?

【问题讨论】:

  • 这可能对你有帮助:stackoverflow.com/questions/5908466/…
  • 谢谢@Meno 但这并不能解决我的问题,因为我只想通过 TestJsonDto 将 TestSet 和 MainQuestion 的几个字段发送到控制器。我的问题是我是否必须创建一个新课程才能做到这一点?

标签: java javascript jquery json spring


【解决方案1】:

你应该这样配置 Spring:

@Configuration
public class ServiceContext
    extends WebMvcConfigurationSupport {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = this.getMappingJackson2HttpMessageConverter();
        converters.add(converter);
    }

    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = this.getObjectMapper();
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        return mappingJackson2HttpMessageConverter;
    }

    @Bean
    public ObjectMapper getObjectMapper() {
        JsonFactory jsonFactory = new JsonFactory();
        ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // this is what you need
        objectMapper.setSerializationInclusion(Include.NON_NULL); // this is to not serialize unset properties
        return objectMapper;
    }
}

这里 Spring 配置了一个 ObjectMapper,它不会序列化值为 null 的属性,并且如果缺少某些属性,反序列化也不会失败。

编辑:(添加了一些背景和解释)

Spring 将 HTTP 请求正文中的内容转换为 POJO(这就是 @RequestBody 实际上告诉 Spring 要做的事情)。此转换由HttpMessageConverter 执行,这是一种抽象。 Spring 为常见的媒体类型提供了默认的特定消息转换器,例如Strings、JSON、表单字段等。

在您的情况下,您需要告诉 Spring 如何反序列化传入的 JSON,即如何读取您从 jQuery 发送的 JSON,以及如何将此 JSON 转换为您希望在您的 @ 中收到的 POJO 987654332@(TestJsonDTO在您的问题中)。

Jackson 2是一个被广泛使用的JSON序列化/反序列化库。它最重要的类是ObjectMapper,用于执行实际的序列化和反序列化。 Spring 有一个特定的HttpMessageConverter,它使用 Jackson 来序列化和反序列化 JSON。这是MappingJackson2HttpMessageConverter,它可以接收Jackson 的ObjectMapper 实例,如果您想覆盖默认行为,您可以配置该实例。

ObjectMapper 配置为不序列化 POJO 中的 null 属性(即,您的 JSON 不会包含这些属性作为字段),更重要的是,在反序列化时,它配置为不会因如果您的 JSON 或 POJO 中缺少属性,则会出现异常。这就是objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 实际所做的。

【讨论】:

  • 谢谢 Magnamg 这对我来说非常有用。但是请你详细说明你的答案,谢谢你
  • magnamag ,抱歉再次打扰,但我又遇到了问题 帖子还可以,但我收到 415 错误。是的,我看过其他相关帖子,但没有一个解决了我的问题。
  • @SumitShrestha 415 表示不受支持的媒体类型。这意味着服务器在响应中使用 Content-Type 标头进行响应,这与您在请求的 Accept 标头中发送的标头不同。请求中的AcceptContent-Type 标头以及响应中的Content-Type 标头都应为application/json。有时会在 Content-Type 标头中添加一个字符集,即 application/json; charset=utf8。也许您收到 415 是因为请求的 Accept 标头只是 application/json,而响应的 Content-Type 标头也包含字符集。
  • @SumitShrestha 是的,你应该发布另一个问题 ;)
  • 这里是问题stackoverflow.com/questions/28271304/…的链接>如果您在答案中也添加代码,那就太好了。提前谢谢你
猜你喜欢
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 2012-12-23
  • 2017-06-12
  • 2011-12-09
  • 2023-03-11
相关资源
最近更新 更多