【问题标题】:json Can not deserialize value of type byte from Stringjson 无法从字符串反序列化字节类型的值
【发布时间】:2017-03-24 20:27:12
【问题描述】:

在 Spring java 应用程序中,我正在接收带有以下输入的 REST json 请求,其中“mode”字段在 java 类中定义为字节。

{
  "application": "sadsd",
  "date": "20161109",
  "mode": "A",
  "catalogId": 0,
}

pojo -

public class Test {
  String application;
  String date;
  byte mode;
  int catalogId;
...
}

出现跟随错误 -

"exception": org.springframework.http.converter.HttpMessageNotReadableException",
  "message": "Could not read document: Can not deserialize value of type byte from String \"A\":
not a valid Byte value\n at 
[Source: java.io.PushbackInputStream@6386b197; line: xx, column: xx] 
(through reference chain: com.abc.myInput[\"mode\"]); 

`enter code here`nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
Can not deserialize value of type byte from String \"A\":

not a valid Byte value\n at [Source: java.io.PushbackInputStream@6386b197; line: xx, column: xx] 
(through reference chain: com.abc.myInput[\"mode\"])",`

我必须在这里编写序列化器和反序列化器吗?
是否有任何注释可以在字节字段或该字段的 get/set 方法上使用而无需编写任何额外代码?

【问题讨论】:

  • 为什么模型不能使用String变量? JSON 没有字节数组的概念。你也许可以编写你的 setter 和 getter 来使用 String 类的构造函数来使用字节数组
  • 由于模型是由许多其他人生成和使用的,因此不能更改数据类型。
  • 那么你需要一个自定义的反序列化器。
  • 我知道这有点啰嗦,但您可以使用 GSON 并编写一个小字节 [] 适配器。看看这个帖子——它几乎把它交给了你。 stackoverflow.com/questions/25522309/…
  • 如果你有一个文件对象作为字节数组呢?

标签: java json jackson


【解决方案1】:

我只是继续将它们声明为字符串并从输入字符串中获取第一个字节并将字节转换为字符串以用于输出。
感谢输入 cricket_007 和 jnbbender。

【讨论】:

  • 你能举个例子吗?
猜你喜欢
  • 2019-08-09
  • 2020-07-26
  • 2019-06-16
  • 2019-11-24
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多