Controller如何接收具有日期属性的实体 no int/Int-argument constructor/factory method to deserialize from Number va

代码

控制器代码

package com.example.demo.controller;
import com.alibaba.fastjson.*;
import org.springframework.web.bind.annotation.*;
import com.example.demo.vo.VO;

@RestController
@RequestMapping("/index")
public class IndexController
{
    
    
	@PostMapping
	public String post(@RequestBody VO vo)
	{
    
    
		System.out.println(JSON.toJSONString(vo));
		return JSON.toJSONString(vo);
	}
}

实体类代码

package com.example.demo.vo;

import lombok.*;
import org.springframework.stereotype.Component;
import java.sql.*;

@Setter
@Getter
@Component
public class VO
{
    
    
	private Time time;
	private Date date;
	private Timestamp timeStamp;
}

测试请求

  1. 请求体中的日期时间已经格式化:
    {
          
          
    	"time":"20:00:00",
    	"date":"2000-10-03",
    	"timeStamp":1634214249564
    }
    
    输出{"date":970531200000,"time":"20:00:00","timeStamp":1634214249564}
  2. 日期时间全是数字类型:
    {
          
          
    	"time":43200000,
    	"date":1635004800000,
    	"timeStamp":1634214249564
    }
    
    输出nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.sql.Time` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (43200000)

出现这样的问题说明SpringBoot里的FastJSON还没正确配置。

解决办法

增加配置类(或者看看自己的配置类是不是少了注解):

package com.example.demo.config;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;

@Configuration
public class JSONConfig
{
    
    
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters()
	{
    
    
		FastJsonConfig conf = new FastJsonConfig();
		FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
		convert.setFastJsonConfig(conf);
		return new HttpMessageConverters(convert);
	}
}

然后对于未格式化请求:

{
    
    
	"time":43200000,
	"date":1635004800000,
	"timeStamp":1634214249564
}

有输出:{"date":"2021-10-24","time":"20:00:00","timeStamp":1634214249564}

猜你喜欢

转载自blog.csdn.net/dscn15848078969/article/details/120771679