Umarshalling MonthDay春季杰克逊JSON [英] Umarshalling MonthDay spring jackson json

查看:51
本文介绍了Umarshalling MonthDay春季杰克逊JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试提供宁静的服务以保存"PeriodeEnseignement",如下所示:

Trying to make a restful service to save " PeriodeEnseignement " as below:

package DomainModel.Enseignement.Notations;

import java.time.MonthDay;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;

import DomainModel.Enseignement.UniteeEnseignement;

@Entity
@Table(name = "PERIODES_ENSEIGNEMENTS")
public class PeriodeEnseignement implements UniteeEnseignement {

    private Integer id;
    private String nom;
    private MonthDay debut;
    private MonthDay fin;

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "UseExistingOrGenerateIdGenerator")
    @GenericGenerator(name = "UseExistingOrGenerateIdGenerator", strategy = "UsefulEntities.UseExistingOrGenerateIdGenerator")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Basic
    @Column(name = "NOM")
    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    @JsonFormat(pattern = "dd/MM")
    @DateTimeFormat(pattern = "dd/MM")
    public MonthDay getDebut() {
        return debut;
    }

    public void setDebut(MonthDay debut) {
        this.debut = debut;
    }

    @JsonFormat(pattern = "dd/MM")
    @DateTimeFormat(pattern = "dd/MM")
    public MonthDay getFin() {
        return fin;
    }

    public void setFin(MonthDay fin) {
        this.fin = fin;
    }
}

但是通过以下方式,带注释的字段出了问题:

But something is going wrong with the annotated fields by:

@JsonFormat(pattern = "dd/MM")
@DateTimeFormat(pattern = "dd/MM")

我已经保留了一些其他实体,并且像咒符一样工作,但是它们不包含MonthDay属性(它与包含LocalDate的实体配合正常).

I've already persisted some other entities and works like a charm but they don't contain MonthDay attributes (it works fine with entities that contain LocalDate).

这是我的restfulcontroller:

here's my restfulcontroller:

@RestController
public class PeriodeEnseignementServices implements GenericUniteeEnseignementService<PeriodeEnseignement> {

@RequestMapping(value = "/periodeEnseignementService/registerPeriodeEnseignementService", method = RequestMethod.POST)
    private GenericResponse registerPeriodeEnseignement(PeriodeEnseignement periodeEnseignement) {
        return this.insertNewUniteeEnseignement(periodeEnseignement, this.periodeEnseignementRepository);
    }
}

在客户端,出现此错误:

In the client-side, i got this error:

jquery-3.3.1.js:9600 POST http://localhost:8080/periodeEnseignementService/registerPeriodeEnseignementService 400

那么如何正确编组/取消编组MonthDay属性呢?

So how to properly marshall / unmarshall MonthDay attributes ?

预先感谢

{timestamp: 1552686924075, status: 400, error: "Bad Request", errors: [{,…}, {,…}],…}
error: "Bad Request"
errors: [{,…}, {,…}]
0: {,…}
arguments: [{codes: ["periodeEnseignement.debut", "debut"], arguments: null, defaultMessage: "debut",…}]
0: {codes: ["periodeEnseignement.debut", "debut"], arguments: null, defaultMessage: "debut",…}
arguments: null
code: "debut"
codes: ["periodeEnseignement.debut", "debut"]
0: "periodeEnseignement.debut"
1: "debut"
defaultMessage: "debut"
bindingFailure: true
code: "typeMismatch"
codes: ["typeMismatch.periodeEnseignement.debut", "typeMismatch.debut", "typeMismatch.java.time.MonthDay",…]
0: "typeMismatch.periodeEnseignement.debut"
1: "typeMismatch.debut"
2: "typeMismatch.java.time.MonthDay"
3: "typeMismatch"
defaultMessage: "Failed to convert property value of type 'java.lang.String' to required type 'java.time.MonthDay' for property 'debut'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat @org.springframework.format.annotation.DateTimeFormat java.time.MonthDay] for value '07/02'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [07/02]"
field: "debut"
objectName: "periodeEnseignement"
rejectedValue: "07/02"
1: {,…}
arguments: [{codes: ["periodeEnseignement.fin", "fin"], arguments: null, defaultMessage: "fin", code: "fin"}]
0: {codes: ["periodeEnseignement.fin", "fin"], arguments: null, defaultMessage: "fin", code: "fin"}
arguments: null
code: "fin"
codes: ["periodeEnseignement.fin", "fin"]
0: "periodeEnseignement.fin"
1: "fin"
defaultMessage: "fin"
bindingFailure: true
code: "typeMismatch"
codes: ["typeMismatch.periodeEnseignement.fin", "typeMismatch.fin", "typeMismatch.java.time.MonthDay",…]
0: "typeMismatch.periodeEnseignement.fin"
1: "typeMismatch.fin"
2: "typeMismatch.java.time.MonthDay"
3: "typeMismatch"
defaultMessage: "Failed to convert property value of type 'java.lang.String' to required type 'java.time.MonthDay' for property 'fin'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat @org.springframework.format.annotation.DateTimeFormat java.time.MonthDay] for value '01/12'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [01/12]"
field: "fin"
objectName: "periodeEnseignement"
rejectedValue: "01/12"
message: "Validation failed for object='periodeEnseignement'. Error count: 2"
path: "/periodeEnseignementService/registerPeriodeEnseignementService"
status: 400
timestamp: 1552686924075

从属性中删除@DateTimeFormat之后,添加@RequestBody并公开了register方法,我在客户端的控制台中遇到了另一个错误:

After removing @DateTimeFormat from attributes, adding @RequestBody and making the register method public i got another error in the client's console:

POST http://localhost:8080/periodeEnseignementService/registerPeriodeEnseignementService 415
send @ jquery-3.3.1.js:9600
ajax @ jquery-3.3.1.js:9206
jQuery.(anonymous function) @ jquery-3.3.1.js:9355
(anonymous) @ utils_end_file.js:13
dispatch @ jquery-3.3.1.js:5183
elemData.handle @ jquery-3.3.1.js:4991


error: "Unsupported Media Type"
message: "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"
path: "/periodeEnseignementService/registerPeriodeEnseignementService"
status: 415
timestamp: 1552811644305

从客户端的post更改为ajax发送json格式请求后,我又遇到了另一个错误

After changing from post to ajax in client-side to send json format request, i got another error

error: "Bad Request"
message: "JSON parse error: Cannot construct instance of `DomainModel.Enseignement.Notations.PeriodeEnseignement` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('id=5&nom=sdsdfsfd&debut=13%2F03&fin=17%2F03'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `DomainModel.Enseignement.Notations.PeriodeEnseignement` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('id=5&nom=sdsdfsfd&debut=13%2F03&fin=17%2F03')↵ at [Source: (PushbackInputStream); line: 1, column: 1]"
path: "/periodeEnseignementService/registerPeriodeEnseignementService"
status: 400
timestamp: 1552820002498

注意:PeriodeEnseignement确实具有默认构造函数.

Note: PeriodeEnseignement does have a default constructor.

推荐答案

我终于通过几处修改解决了这个问题.

I finally solved the problem with several modifications.

1-将客户端调用从jQuery.post更改为$ .ajax调用,如下所示

1- Changing client-side call from jQuery.post to $.ajax call as shown here

var form = $('#myForm');
var jsonFormData = getFormData(form);

$.ajax({
            url : "/path/to/web/service/controller",
            type : "POST",
            dataType : "json",
            contentType : "application/json",
            data : JSON.stringify(jsonFormData),

            complete : function() {
            },

            success : function(data) {
                alert("success !");
            },

            error : function() {
                alert("failed !");
            },
        });
    });

function getFormData($form) {
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i) {
        indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}

2-在我的服务端例程中添加了@RequestBody:

2- Added @RequestBody to my service-side routine:

@RequestMapping(value = "/periodeEnseignementService/registerPeriodeEnseignementService", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public GenericResponse registerPeriodeEnseignement(@RequestBody PeriodeEnseignement periodeEnseignement) {
    return this.insertNewUniteeEnseignement(periodeEnseignement, this.periodeEnseignementRepository);
}

3- POJO类中不需要@DateTimeFormatter或@JsonFormat("dd/MMM").

3- No need for @DateTimeFormatter neither @JsonFormat("dd/MMM") in the POJO class.

4-必须为java.time.MonthDay配置一个JsonSerializer和一个JsonDeserializer,否则,这些字段将保留为空.

4- Had to configure a JsonSerializer and a JsonDeserializer for java.time.MonthDay, otherwise, the fields were left null.

@Bean
    public ObjectMapper objectMapperBuilder() {
        SimpleModule msJavaTimeModule = new SimpleModule();

        msJavaTimeModule.addSerializer(MonthDay.class, new JsonSerializer<MonthDay>() {
            @Override
            public void serialize(MonthDay value, JsonGenerator gen, SerializerProvider serializers)
                    throws IOException {
                gen.writeStartObject();
                gen.writeStringField("label", value.format(DateTimeFormatter.ofPattern("dd MMM", Locale.FRANCE)));
                gen.writeEndObject();
            }
        });

        msJavaTimeModule.addDeserializer(MonthDay.class, new JsonDeserializer<MonthDay>() {

            @Override
            public MonthDay deserialize(JsonParser p, DeserializationContext ctxt)
                    throws IOException, JsonProcessingException {
                JsonNode node = p.getCodec().readTree(p);

                String content = node.asText();

                int slashIndex = content.indexOf('/');

                String dayAsString = content.substring(0, slashIndex);
                String monthAsString = content.substring(slashIndex + 1);

                int day = Integer.parseInt(dayAsString);
                int month = Integer.parseInt(monthAsString);

                return MonthDay.of(month, day);
            }
        });

        ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder().modules(msJavaTimeModule).build();

        return objectMapper;
    }

感谢MichałZiober的指导!

Thanks to Michał Ziober for the guidance !

这篇关于Umarshalling MonthDay春季杰克逊JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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