解析是对象或对象数组的JSON密钥 [英] Parse JSON key that is either object or array of object

查看:175
本文介绍了解析是对象或对象数组的JSON密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Moshi中,是否可以创建一个类型适配器来解析一个对象或相同类型的对象列表?

In Mos is it possible to create a type adapter that would parse both an object or a list of objects of the same type?

例如,有时JSON是:

For example, sometimes the JSON is:

{
  "person": {...}
}

其他时间是

{
  "person": [{...}, {...}]
}

理想情况下,我希望有一个如下所示的Java对象:

Ideally, I'd want to have a Java object looking like this:

class PersonContainer {
  @PersonsList List<Person> persons; // @List(Person.class) would be even better
}

推荐答案

我建议您按照您所说的做一个适配器.
创建一个函数(适配器)以检查它是单个对象还是数组(可能基于'['char),并且适配器会将输入定向到正确的处理函数.

I would suggest you make just what you said, an adapter.
make a function(the adapter) to check whether its a single object or an array, probably based on the '[' char and the adapter will direct the input into the right handling function.

另一种方法是假设所有输入都是数组,并从那里开始工作.

another method is to assume all the input is arrays and work from there.

这篇关于解析是对象或对象数组的JSON密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆