import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.io.IOException; @Component public class JsonBooleanDeserializer extends JsonDeserializer<Boolean> { /*** * 兼容sql92 bit数据类型 0(false) 1(true) * @param parser * @param ctxt * @return * @throws IOException * @throws JsonProcessingException */ @Override public Boolean deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { String value = parser.getText(); if(StringUtils.isBlank(value)) { return null; } //here we treat 1 as true, 0 false if(Boolean.valueOf(StringUtils.equals("1",value))) { return Boolean.TRUE; } if(Boolean.valueOf(StringUtils.equals("on",value))) //for checkbox component { return Boolean.TRUE; } if(Boolean.valueOf(StringUtils.equals("0",value))) { return Boolean.FALSE; } if(Boolean.valueOf(StringUtils.equalsIgnoreCase("true",value))) { return Boolean.TRUE; } if(Boolean.valueOf(StringUtils.equalsIgnoreCase("false",value))) { return Boolean.FALSE; } throw new RuntimeException("unsupported conversion from ["+value+"] to Boolean."); } }
实现目的:
将 数据库 bit类型的0,1分别转换成Boolean类型的False和true
将短日期格式2019-01-01转换成LocalDate类的实例
将日期时间格式的数据2019-01-01 10:10:10转换成LocalDateTime的实例
前端数据
<input type="radio" name="f_scjafs" value="1">接受 <input type="radio" name="f_scjafs" checked="" value="0">取消 <input style="299px;" id="f_wxdkhqzrq" name="f_wxdkhqzrq" type="text" class="input" onfocus="WdatePicker({isShowToday:true,dateFmt:'yyyy-MM-dd',readOnly:true})" value="2019-05-07"> <input autocomplete="off" name="f_sqsj" id="f_sqsj" type="text" maxlength="100" onfocus="WdatePicker({isShowToday:true,dateFmt:'yyyy-MM-dd HH:mm:ss',readOnly:true})" value="2019-05-29 16:35:14" class="input1">
后端结果
前端代码
<script type="text/javascript" src="${ctx}/js/jquery.serializejson.min.js"></script> <script> var data = {}; data = $("#form1").serializeJSON(); var issueProcess = []; $("#sjcljl .list").each(function(index,item) { var step = index+1; var record ={}; record.id = replaceNull($(item).find('input[id="issueProcessId'+step+'"]').val()); record.f_clsm = replaceNull($(item).find('textarea[id="f_clsm'+step+'"]').val()); record.f_fk = replaceNull($(item).find('select[id="f_fk'+step+'"]').val()); record.f_clkssj = replaceNull($(item).find('input[id="f_clkssj'+step+'"]').val()); record.f_cljssj = replaceNull($(item).find('input[id="f_cljssj'+step+'"]').val()); record.f_clryid = replaceNull($(item).find('input[id="f_clry1'+step+'"]').attr("f_clryid1"+step)); //至少填写开始、结束时间 if(!(isNull(record.f_clkssj)|| isNull(record.f_cljssj) ||isNull(record.f_clryid))) { issueProcess.push(record); } }); data.issueProcess = issueProcess; $.ajax({ type: "POST", url: "/itss/issue/save", dataType: 'json', contentType : 'application/json;charset=utf-8', data: JSON.stringify(data), success: function (resp) { //处理代码 }, error: function (err) { layer.alert(err.responseText, { offset: '200px', }); } }); function replaceNull(val){ if(val==undefined || val==null || val=="" || val=='' || val=='null' || val=='-1' ||val.length<parseInt(1)){ return null; }else{ return val; } } </script>
后端代码
/*** * 问题保存 * @param model * @return */ @RequestMapping(value = "/save", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public ReturnParam save(@RequestBody UserIssueDto model) { ReturnParam rp = new ReturnParam(); Integer id = model.getId(); if (id>0) { ///.... } else { ///.... } return rp; } public class ReturnParam { private Object result; private String desc; private String status; private String wybs; public String getWybs() { return wybs; } public void setWybs(String wybs) { this.wybs = wybs; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } public class UserIssueDto implements Serializable { @JSONField(format = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonSerialize(using= JsonLocalDateTimeSerializer.class) @JsonDeserialize(using= JsonLocalDateTimeDeserializer.class) private LocalDateTime f_sqsj; //申请时间 @JsonSerialize(using= JsonBooleanSerializer.class) @JsonDeserialize(using= JsonBooleanDeserializer.class) private Boolean f_scjafs; //审查结案方式:0拒绝 1接受 @DateTimeFormat(pattern = "yyyy-MM-dd") @JsonSerialize(using= JsonLocalDateSerializer.class) @JsonDeserialize(using= JsonLocalDateDeserializer.class) private LocalDate f_wxdkhqzrq;// 维修单客户签字日期 //... }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.stereotype.Component; import java.io.IOException; @Component public class JsonBooleanSerializer extends JsonSerializer<Boolean> { @Override public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException{ if(null == value) { gen.writeString((String)null); } gen.writeBoolean(Boolean.TRUE.equals(value)); } }
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.io.IOException; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /*** * 兼容jsr310的LocalDate JSON反序列化类 */ @Component public class JsonLocalDateDeserializer extends JsonDeserializer<LocalDate> { @Override public LocalDate deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException{ String szLocalDate = parser.getText(); if(StringUtils.isBlank(szLocalDate)) { System.err.println("invalid date supplied for conversion,ignored."); return null; } return LocalDate.parse(parser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.of("GMT+8"))); } }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.stereotype.Component; import java.io.IOException; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /*** * 兼容jsr310的LocalDate JSON序列化类 */ @Component public class JsonLocalDateSerializer extends JsonSerializer<LocalDate> { @Override public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException{ if(value == null) { System.err.println("invalid date supplied for conversion,ignored."); return; } String formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.of("GMT+8")).format(value); gen.writeString(formattedDate); } }
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /*** * 兼容jsr310的LocalDateTime JSON反序列化类 */ @Component public class JsonLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { @Override public LocalDateTime deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException{ String szLocalDateTime = parser.getText(); if(StringUtils.isBlank(szLocalDateTime)) { System.err.println("invalid date supplied for conversion,ignored."); return null; } return LocalDateTime.parse(parser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("GMT+8"))); } }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.stereotype.Component; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /*** * 兼容jsr310的LocalDateTime JSON序列化类 */ @Component public class JsonLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException{ if(value ==null) { System.err.println("invalid date supplied for conversion,ignored."); return; } String formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("GMT+8")).format(value); gen.writeString(formattedDate); } }
相关依赖及版本:
commons-lang3-3.3.2.jar
fastjson-1.2.12.jar
jackson-datatype-jsr310-2.9.8.jar
spring 4.2.7
实际数据转换效果