使用Jackson读取空字符串值作为对象,并使用null属性
之类的值
我有一个API请求来处理有时用代码200返回的API请求,以及{“ key”:“ value”}
,但在某些情况下,API可能会使用代码204返回。处理此操作是其他故事一个空字符串,因此不会抛出NosuchelementException。
现在,我想以某种方式处理杰克逊的结果,在200个情况下,我会得到一个类似这样描述的类A的对象:
class A(@JsonProperty("key") val value: String?)
但是在204和空体反应的情况下,我想获得一个实例a带有value
属性等于null
。
我已经尝试添加一个自定义的Deserialiser,但是甚至在执行Deserialiser代码之前,我都会得到以下异常:
com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input at [Source: (String)""; line: 1, column: 0]
这很明显,因为空字符串中没有顶级JSON对象。
有什么方法可以使用杰克逊实现所需的行为?
I have an API request to handle that sometimes returns with code 200 and a value of something like
{ "key" : "value" }
But in some cases, API might return with code 204. Handling this is a whole other story, but I end up with an interceptor that replaces a response body with an empty string, so it won't throw NoSuchElementException.
Now I want to handle the result with Jackson in a way, that in a case of 200 I would get an object of class A described like this:
class A(@JsonProperty("key") val value: String?)
But in the case of 204 and empty body response, I would like to get an instance of A with value
property equals null
.
I've tried adding a custom deserialiser, but I get the following exception even before my deserialiser code is executed:
com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input at [Source: (String)""; line: 1, column: 0]
This is kind of obvious since there's no top-level JSON object in an empty string.
Is there a way I can achieve desired behaviour using Jackson?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不熟悉杰克逊,但我注意到你说
而不是空字符串返回
“ {\” key \ \“:null}”
而不是吗?I'm not familiar with Jackson but I notice you said
Can't you just then instead of empty string return
"{ \"key\" : null }"
instead?