简体   繁体   English

我们是否必须使用与控制器中的pojo对象完全相同的字段发布json对象?

[英]Do we have to have to post json object with exactly same fields as in pojo object in controller?

I am new to spring rest and am having problem to map JSON object from jquery to controller. 我是新手休息,我有问题将JSON对象从jquery映射到控制器。 My jquery JSON object have some field absent which are present in java object on controller. 我的jquery JSON对象有一些字段缺席,它们存在于控制器上的java对象中。 Do I have to create new class to map such object or is there any way to map these objects without creating new class? 我是否必须创建新类来映射此类对象,或者有没有办法在不创建新类的情况下映射这些对象?

Here are the code 这是代码

Controller: 控制器:

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

TestJsonDTO: 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: MainQuestion:

public class MainQuestion implements Serializable {

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

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

and my jquery post method 和我的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()
    })

}

In JSON.stringify I am not sending all the fields in TestJsonDto . JSON.stringify我没有发送TestJsonDto所有字段。 How can I map this? 我该如何映射?

You should configure Spring this way: 你应该这样配置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;
    }
}

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. 这里,Spring配置了一个ObjectMapper ,它不会序列化值为null属性,并且如果缺少某些属性,则在反序列化时不会失败。

EDIT: (Added some background and explanations) 编辑:(添加了一些背景和解释)

Spring converts what comes in HTTP request's body into a POJO (that's what @RequestBody actually tells Spring to do). Spring将HTTP请求主体中的内容转换为POJO(这就是@RequestBody实际上告诉Spring要做的事情)。 This conversion is performed by a HttpMessageConverter , which is an abstraction. 此转换由HttpMessageConverter执行,这是一个抽象。 Spring provides default specific message converters for common media types, such as String s, JSON, form fields, etc. Spring为常见媒体类型提供默认的特定消息转换器,例如String ,JSON,表单字段等。

In your case, you need to tell Spring how to deserialize the incoming JSON, ie 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). 在您的情况下,您需要告诉Spring如何反序列化传入的JSON,即如何读取您从jQuery发送的JSON以及如何将此JSON转换为您期望在@Controller接收的POJO( TestJsonDTO在你的问题)。

Jackson 2 is a JSON serialization/deserialization library that is widely used. Jackson 2是一个广泛使用的JSON序列化/反序列化库。 It's most important class is ObjectMapper , which is used to perform the actual serialization and deserialization. 最重要的类是ObjectMapper ,它用于执行实际的序列化和反序列化。 Spring has a specific HttpMessageConverter that uses Jackson in order to serialize and deserialize JSON. Spring有一个特定的HttpMessageConverter ,它使用Jackson来序列化和反序列化JSON。 This is MappingJackson2HttpMessageConverter , which can receive a Jackson's ObjectMapper instance that you can configure if you want to override default behavior. 这是MappingJackson2HttpMessageConverter ,它可以接收Jackson的ObjectMapper实例,如果要覆盖默认行为,可以配置该实例。

This ObjectMapper is configured to not serialize properties that are null in your POJO (ie 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. ObjectMapper配置为不序列化POJO中为null属性(即,您的JSON不会将这些属性包含为字段),更重要的是,在反序列化时,如果缺少属性,则将其配置为不会因异常而失败在你的JSON或你的POJO中。 This is what objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 这就是objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); actually does. 实际上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM