无法从 START_OBJECT 令牌中反序列化 java.util.date 实例

huangapple go评论83阅读模式
英文:

Cannot deserialize instance of 'java.util.date' out of START_OBJECT token

问题

Invalid JSON input: 无法从START_OBJECT令牌中反序列化java.util.Date实例; 嵌套异常是com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法从START_OBJECT令牌中反序列化java.util.Date实例

我正在尝试在REACT中使用函数组件和useState()将默认日期选择器设置为显示太平洋时间。

REACT

const [startDate, setStartDate] = useState(new Date());
return (
  <TextField
    id="datetime-local-startTime"
    type="datetime-local"
    defaultValue={startDate}
    className={classes.textField}
    onChange={setDefaultStartDate(startDate)}
  />
);
const setDefaultStartDate = (date) => {
  date.setHours(date.getHours() - 8);
  setStartDate(date.toISOString().substr(0, 16));
  return date.toISOString().substr(0, 16);
}

JAVA

@JsonProperty("startDate")
private Date startDate;

@JsonProperty("endDate")
private Date endDate;

请注意,我已经将代码中的HTML实体编码还原为正常的HTML标记。

英文:

Invalid JSON input: Cannot deserialize instance of java.util.Date out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of ``java.util.Date` out of START_OBJECT token

I am trying to set the default date picker to show pacific time in REACT using functional Component. useState()

REACT

const [startDate, setStartDate] = useState(new Date());
return(&lt;TextField
         id=&quot;datetime-local-startTime&quot;
         type=&quot;datetime-local&quot;
         defaultValue={startDate}
         className={classes.textField}
         onChange={setDefaultStartDate(startDate)}
       /&gt;)
const setDefaultStartDate = (date) =&gt; {
        date.setHours(date.getHours() - 8);
        setStartDate(date.toISOString().substr(0, 16))
        return date.toISOString().substr(0, 16);
    }

JAVA

@JsonProperty(&quot;startDate&quot;)
private Date startDate;
	
@JsonProperty(&quot;endDate&quot;)
private Date endDate;`

答案1

得分: 1

这里发生的情况是,React 的日期不是一个字符串,而是一个复杂的对象。当你将该对象作为请求的一部分发送时,Jackson 期望在服务器端找到相同的类定义进行反序列化。换句话说,React 的日期类不等于 Java 的日期类。你需要在 Java 端为此日期定义一个自定义的 Jackson 反序列化器,或者将 React 的日期转换为一个简单的字符串,以便 Jackson 可以进行反序列化。

英文:

What is happening here is that the react date is not a string but a complex object. When you send that object up as part of the request, Jackson is expecting to find a the same class definition on the server side to deserialize into. In other words, react date class != java date class. You either need to define a custom jackson Deserializer for this date on the Java side, or convert the react date into a simple string that can be deserialized by Jackson.

huangapple
  • 本文由 发表于 2020年4月9日 20:24:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61121106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定