使用 Google 的 Gson 反序列化 Bugzilla JSON 时出现问题
我在从 Bugzilla 服务器返回的 JSON 中遇到问题,因为它有时返回“text”:{},有时返回“text”:“blah blah blah”。如果没有给出 bug 的描述,Bugzilla 将返回前者。我很困惑为什么它没有以更明智的“文本”形式出现:“”但它确实出现了,就是这样。
如果我在 Gson 的目标对象中有一个名为 text 的字符串,当它看到 {} 情况时它会反对,因为它说这是一个对象而不是字符串:
Exception in thread "main" com.google.gson.JsonParseException: The
JsonDeserializer StringTypeAdapter failed to deserialized json object {} given
the type class java.lang.String
关于如何让 Gson 解析它有什么建议吗?
I'm hitting a problem in JSON I'm getting back from a Bugzilla server because it sometimes returns "text" : {} and sometimes "text" : "blah blah blah". Bugzilla returns the former if no description was given for a bug. I'm mystified why it doesn't come back as the much more sensible "text" : "" but it does and that's it.
If I have a String named text in the target object for Gson, it objects when it sees the {} case because it says that's an object and not a String:
Exception in thread "main" com.google.gson.JsonParseException: The
JsonDeserializer StringTypeAdapter failed to deserialized json object {} given
the type class java.lang.String
Any suggestions on how I can make Gson parse this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Gson 需要针对原始问题中的情况进行自定义反序列化。以下是这样一个例子。
input.json:
Foo.java:
输出:
使用
Thing.class
类型的自定义反序列化器将当然有可能。这样做的好处是不必为每个String
添加额外的处理,但随后您将不得不“手动”处理Thing
的所有其他属性。Gson requires custom deserialization for the situation in the original question. Following is one such example.
input.json:
Foo.java:
Output:
Using instead a custom deserializer for the
Thing.class
type would of course be possible. This would have the benefit of not adding additional processing for everyString
, but then you'd be stuck with "manual" processing all of the other attributes ofThing
.尝试将
text
字段声明为Object
。然后执行以下操作:您应该将此作为错误报告给 Bugzilla 项目。这种行为没有充分的理由。
Try declaring the
text
field to be anObject
. Then do something like:You should report this as a bug to the Bugzilla project. There's no good reason for this behavior.