使用 GSON 解析没有特定字段结构的 JSON
我正在使用 EmpireAvenue API 开发 Android 应用程序。 API 使用 JSON,我使用 GSON 库来解析来自 API 的数据。 问题是:
我有一个像这样的 JSON 结构:
{
type: "earnings",
info: {
earnings: 64.09
dividends: 1277.34
gains: 1997.05
expenses: 4895.51
shares_bought: 210
shares_bought_user_count: 2
shares_sold: 0
shares_sold_user_count: 0
},
created: "2011-04-16 11:32:37"
},
{
type: "following",
info: [
{
ticker: "SOLPHE"
full_name: "Rodrigo Bermudez Salazar"
list_name: "My Recommended Buys"
},
{
ticker: "SOLPHE"
full_name: "Rodrigo Bermudez Salazar"
list_name: "My Watch List"
}
],
created: "2011-04-16 11:00:08"
}
如您所见,与 info 字段关联的结构是不同的。有时它是一个对象,有时是一个数组。正如预期的那样,GSON 库在解析时会抛出错误。 你知道当字段改变结构时如何解析 JSON 结构吗?
感谢您的帮助。
I am working on an Android application, using the EmpireAvenue API.
The API uses JSON and I'm using the GSON library to parse the data from the API.
Here is the problem:
I have a JSON structure like this:
{
type: "earnings",
info: {
earnings: 64.09
dividends: 1277.34
gains: 1997.05
expenses: 4895.51
shares_bought: 210
shares_bought_user_count: 2
shares_sold: 0
shares_sold_user_count: 0
},
created: "2011-04-16 11:32:37"
},
{
type: "following",
info: [
{
ticker: "SOLPHE"
full_name: "Rodrigo Bermudez Salazar"
list_name: "My Recommended Buys"
},
{
ticker: "SOLPHE"
full_name: "Rodrigo Bermudez Salazar"
list_name: "My Watch List"
}
],
created: "2011-04-16 11:00:08"
}
As you can see, the structure associated with the info field is different. Sometimes it's an object, sometimes an array. As expected, the GSON library throws errors when parsing.
Do you know how to parse a JSON structure with when a field changes structure ?
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当前的 Gson 解决方案有点复杂,需要实现自定义实例创建器和/或自定义反序列化器。请查看 http://code.google.com/ p/google-gson/issues/detail?id=231 和 有关分层类型适配器的发行说明了解详细信息。我刚刚发布了一个使用 Gson 进行多态反序列化的示例,以响应 使用 gson 进行多态。
Gson 希望很快就会有 RuntimeTypeAdapter 来实现更简单的多态反序列化。请参阅 http://code.google.com/p/google -gson/issues/detail?id=231 了解更多信息。
另一方面,基于 Jackson 的解决方案也不错。
The current solution with Gson is a bit involved, requiring implementation of a custom Instance Creator and/or a custom Deserializer. Take a look at http://code.google.com/p/google-gson/issues/detail?id=231 and the release notes on Hierarchical Type Adapters for details. I just posted an example of polymorphic deserialization with Gson in response to Polymorphism with gson.
Gson hopefully will soon have the
RuntimeTypeAdapter
for simpler polymorphic deserialization. See http://code.google.com/p/google-gson/issues/detail?id=231 for more info.On the other hand, a Jackson-based solution isn't so bad.