java中有json的数据类型么,处理Java中REST结果(json)中不一致的数据类型

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.

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 setlist;

I also assume your MyItem class contains the field:

@SerializedName("sets")

private List 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值