使用Jackson读取空字符串值作为对象,并使用null属性

发布于 2025-02-04 20:12:55 字数 781 浏览 1 评论 0原文

之类的值

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

面犯桃花 2025-02-11 20:12:55

我不熟悉杰克逊,但我注意到你说

我最终用一个用空字符串替代响应主体的拦截器

而不是空字符串返回“ {\” key \ \“:null}”而不是吗?

I'm not familiar with Jackson but I notice you said

I end up with an interceptor that replaces a response body with an empty string

Can't you just then instead of empty string return "{ \"key\" : null }" instead?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文