Day07

目录

1、使用@JsonIgnoreProperties

2、前端日期字符串转换LocalDateTime异常


1、使用@JsonIgnoreProperties

在做项目时把前端的JSON对象转为dto对象时,出现了异常

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized field "showOption" (class org.example.entity.DishFlavor), not marked as ignorable; nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "showOption" (class org.example.entity.DishFlavor), not marked as ignorable (9 known properties: "value", "updateUser", "dishId", "updateTime", "createUser", "createTime", "id", "isDeleted", "name"]) at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 262] (through reference chain: org.example.dto.DishDto["flavors"]->java.util.ArrayList[0]->org.example.entity.DishFlavor["showOption"])]

意思是Json对象中出现了showOption属性,但是对应的dto对象中没有这个属性,并且showOption属性没有被marked as ignorable,所以反序列化失败

解决方法如下,在反序列化类上添加@JsonIgnoreProperties(ignoreUnknown = true)

作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。将这个注解写在类上之后,就会忽略类中不存在的字段。

@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class DishFlavor implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    .....
}

2、前端日期字符串转换LocalDateTime异常

前端没有采用Json格式发送,而是字符串。SB就不会使用Jackson中的消息转换器,对时间字符串进行转换,并且SB的转换器默认转换格式为:yyyy-MM-dd T HH:mm:ss,所以无法转换成指定格式

Day07_第1张图片

 解决方法如下:在参数上添加@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss"),指明时间格式。

@GetMapping("/page")
    public Result getCategorys(@RequestParam("page") int page, @RequestParam("pageSize") int pageSize,String number, 
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        Page page1 = PageHelper.startPage(page, pageSize);
        List list = orderService.selectOrders(number, beginTime, endTime);
        PageInfo pageInfo = new PageInfo<>(list);
        HashMap map = new HashMap<>();
        map.put("records",list);
        map.put("total", page1.getTotal());
        return Result.success(map);
    }

你可能感兴趣的:(Reggie,java)