【问题标题】:Android Kotlin RxJava Retrofit - Json object that has lists as attributes expected BEGIN_ARRAY but was BEGIN_OBJECTAndroid Kotlin RxJava Retrofit - 具有列表作为属性的 Json 对象预期为 BEGIN_ARRAY 但为 BEGIN_OBJECT
【发布时间】:2019-05-10 20:24:48
【问题描述】:

我从 API 接收到一个 Person 对象,该对象具有另一个对象的列表作为其属性之一。我在日志中收到以下错误:“Expexted BEGIN_ARRAY 但在路径 $ 处是 BEGIN_OBJECT”。所以 JSON 没有正确解析列表。我使用 Moshi 进行 JsonParsing。

Person JSON 对象:(实际项目中有多个人)

{
    "personId": 1,
    "personName": "Bert",
    "personAge": 19,
    "isFemale": "false",
    "dogs": [{
        "dogId": 1,
        "dogName": "Fred",
        "isFemale": "false"
    }, {
        "dogId": 2,
        "dogName": "Laika",
        "isFemale": "true"
    }],
    "birthDate": "2000-06-28T00:00:00"
}

Dog 数据模型类:

data class Dog(
  @Json(name = "dogId")
  val dogId: Int,

  @Json(name = "dogName")
  val name: String,

  @Json(name = "isFemale")
  val isFemale: Boolean,
)

Person 数据模型类:

data class Person (
  @Json(name = "personId")
  val personId: Int,

  @Json(name = "personName")
  val name: String,

  @Json(name = "personAge")
  val age: Int,

  @Json(name = "isFemale")
  val isFemale: Boolean,

  @Json(name = "dogs")
  val dogs: List<Dog>

  @Json(name = "birthDate")
  val birthDate: GregorianCalendar

)

ApiInterface:(注意一个 Person 列表,因为它总是返回一个 Person 对象的列表)

@GET("persons/{personId}")
fun getPerson(@Path("personId") id: Int): Observable<List<Person>>

PersonRepository:

class PersonRepository @Inject constructor(val apiInterface: ApiInterface) {
  fun getPerson(personId: Int): Observable<Person>{
    return apiInterface.getPerson(personId)
      .doOnNext { value -> Log.d("PERSON_LOG_TAG", "onNext: value=$value") }
      .flatmap { response ->
         if(response.size == 1) {
            Observable.just(response[0])
         } else {
            Observable.error(Throwable("Something went wrong")
         }
      }
  } 
}

PERSON_LOG_TAG 给出“预期为 BEGIN_ARRAY 但为 BEGIN_OBJECT 错误”。知道如何解决吗?这通常通过创建一个像 PersonResponse 这样的外部 JSON 类来解决,该类具有真实类的列表。但我不知道如何处理另一个对象中的列表。

【问题讨论】:

    标签: android list kotlin retrofit rx-java


    【解决方案1】:

    如果按约定创建的 API 比 persons/{personId} 应该返回 Person 对象而不是 Person 列表。所以我假设你应该替换

    @GET("persons/{personId}")
    fun getPerson(@Path("personId") id: Int): Observable<List<Person>>
    

    @GET("persons/{personId}")
    fun getPerson(@Path("personId") id: Int): Observable<Person>
    

    【讨论】:

    • 对,因为我之前是从列表中提取的,所以我忘了删除它,谢谢。
    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 2019-05-10
    • 2017-02-14
    • 2016-09-26
    • 1970-01-01
    • 2020-04-06
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多