我们是否必须使用与控制器中的pojo对象完全相同的字段发布json对象? [英] Do we have to have to post json object with exactly same fields as in pojo object in controller?

查看:167
本文介绍了我们是否必须使用与控制器中的pojo对象完全相同的字段发布json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初次休息的新手,我遇到了将JSON对象从jquery映射到控制器的问题。我的jquery JSON对象有一些字段缺席,它们存在于控制器上的java对象中。我是否必须创建新类来映射此类对象,或者有没有办法在不创建新类的情况下映射这些对象?

I am new to spring rest and am having problem to map JSON object from jquery to controller. My jquery JSON object have some field absent which are present in java object on controller. Do I have to create new class to map such object or is there any way to map these objects without creating new class?

以下是代码

控制器:

@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

TestSet:

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;

MainQuestion:

public class MainQuestion implements Serializable {

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

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

和我的jquery post方法

and my jquery post method

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 中的所有字段。我该如何映射?

In JSON.stringify I am not sending all the fields in TestJsonDto. How can I map this?

推荐答案

你应该这样配置Spring:

You should configure Spring this way:

@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 的属性,并且如果缺少某些属性,则在反序列化时不会失败。

Here Spring is configured with an ObjectMapper that doesn't serialize properties whose value is null and that doesn't fail on deserialization if some property is missing.

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

(Added some background and explanations)

Spring转换HTTP请求的内容进入POJO(这就是 @RequestBody 实际上告诉Spring要做的事)。此转换由 HttpMessageConverter ,这是一个抽象。 Spring为常见媒体类型提供默认的特定消息转换器,例如 String s,JSON,表单字段等。

Spring converts what comes in HTTP request's body into a POJO (that's what @RequestBody actually tells Spring to do). This conversion is performed by a HttpMessageConverter, which is an abstraction. Spring provides default specific message converters for common media types, such as Strings, JSON, form fields, etc.

在你的情况下,你需要告诉Spring如何反序列化传入的JSON,即如何读取你从jQuery发送的JSON以及如何将这个JSON转换为你期望在<$ c中收到的POJO $ c> @Controller (问题中 TestJsonDTO )。

In your case, you need to tell Spring how to deserialize the incoming JSON, i.e. how to read the JSON that you're sending from jQuery and how to convert this JSON into the POJO you're expecting to receive in your @Controller (TestJsonDTO in your question).

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

Jackson 2 is a JSON serialization/deserialization library that is widely used. It's most important class is ObjectMapper, which is used to perform the actual serialization and deserialization. Spring has a specific HttpMessageConverter that uses Jackson in order to serialize and deserialize JSON. This is MappingJackson2HttpMessageConverter, which can receive a Jackson's ObjectMapper instance that you can configure if you want to override default behavior.

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

This ObjectMapper is configured to not serialize properties that are null in your POJO (i.e. your JSON won't contain these properties as fields), and more important, when deserializing, it is configured to not fail with an exception if there is a missing property in either your JSON or your POJO. This is what objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); actually does.

这篇关于我们是否必须使用与控制器中的pojo对象完全相同的字段发布json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆