处理Java中REST结果(json)中不一致的数据类型 [英] Handling inconsistent data types in REST results (json) in Java
问题描述
我是新手,试图从Android Studio的setlist.fm上使用Rest API,但在将我的GET请求结果装入我的Java数据模型时遇到了一些问题。
特别是,我已经将sets(set是指在音乐会上演奏的一组作品)建模为Java类。但通常情况下,我从我的HTTP请求中返回结果,它们将设置为空字符串或甚至数组。
我将使用以下GET请求Radiohead setlists为例:
http://api.setlist.fm/rest/0.1/artist/a74b1b7f-71a5-4011-9441-d0b5e4122711/setlists.json
通知大多数情况下,套是一个对象。但在某些情况下,它是字符串。在其他情况下,它是一个数组。
当我尝试使用以下代码行解析带有Gson的json到我的数据模型中时,我的Android Studio给了我以下错误:
gson.fromJson(result.toString(),Response.class);
对于sets显示为空字符串而非对象的实例,它似乎失败:
预计BEGIN_OBJECT,但在第1行的列STRING 942路径$ .setlists.setlist [0] .sets
有没有人有关于如何处理这类事情的建议?我注意到了迄今为止我所看过的所有艺术家。
Thanks!
假设响应
写了包含json的主要字段,并在它的某个点你有:
pre $ @ $ @SerializedName(setlist)
私人列表< MyItem>设置列表;
我还假设您的 MyItem
类包含字段:
@SerializedName(sets)
private List< MySet>套;
如果让 Gson
解析它,它会当它发现一个字符串而不是MySet对象的列表( - >数组)时失败。
但是你可以为 TypeAdapter
> MyItem 。
有很多关于如何编写Gson TypeAdapter的文档,请查看它。
I'm new, and attempting to work with the Rest API on setlist.fm from Android Studio, but am having some issues when fitting my GET request results into my Java data model. Particularly, I have modeled "sets" ("set" refers to a set played at a concert) as a Java class. But commonly, I get results back from my HTTP requests that have "set" as an empty string or even an array.
I'll use this following GET request for all Radiohead setlists as an example: http://api.setlist.fm/rest/0.1/artist/a74b1b7f-71a5-4011-9441-d0b5e4122711/setlists.json
Notice how, for the most part, "sets" is an object. But in some instances, it is a String. In other instances it is an array.
My Android Studio is giving me the following error when I try to parse the json with Gson into my data model using the following line of code:
gson.fromJson(result.toString(),Response.class);
It appears to be failing on an instance where "sets" is shown an empty string rather than an object:
Expected BEGIN_OBJECT but was STRING at line 1 column 942 path $.setlists.setlist[0].sets
Does anyone have advice on how to handle this type of thing? I've noticed it with all artists I've looked up so far. Thanks!
Assuming Response
is a class you wrote containing the main fields of the json and that at some point in it you have:
@SerializedName("setlist")
private List<MyItem> setlist;
I also assume your MyItem
class contains the field:
@SerializedName("sets")
private List<MySet> sets;
if you let Gson
parse it it will fail when it found a string instead of a list (-> array) of MySet object.
But you can write a custom TypeAdapter
for your MyItem
.
There's plenty of documentation about how to write a Gson TypeAdapter, look for it.
这篇关于处理Java中REST结果(json)中不一致的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!