Why can't I fetch nested data from json using Gson?

£可爱£侵袭症+ 提交于 2021-01-29 07:11:58

问题


I have a json I fetch from an API that looks like this:

{"success":true,"message":"","result":{"Bid":6886.97100000,"Ask":6891.58500000,"Last":6891.58500000}}

All I want is to just save Bid and Ask values in fields of a class.

First I parse whole json like this:

   val response = sendRequest(url))
   val gson = Gson()
   val ticker : MarketTickerEntity = gson.fromJson(response, MarketTickerEntity::class.java)

And then I try to parse it inside of my class init block and reassign to bid and ask fields.

My class:

class MarketTickerEntity(@SerializedName("result")val result: JsonObject? = null) : TickerEntity {

  override val fee: Double = 0.0001
  override var bid: Double = 0.0
  override var ask: Double = 0.0

  data class ResultData (
    val Bid: Double,
    val Ask: Double,
    val Last: Double
  )

  init {
    if(result != null) {
      val gson = Gson()
      val res: ResultData = gson.fromJson(result, ResultData::class.java)
      bid = res.Bid
      ask = res.Ask
    }
  }

}

But unfortunately result is always null.

I have tried changing JsonObject? to String? in result type and then I get the error:

Expected a string but was BEGIN_OBJECT at line 1 column 40 path $.result

回答1:


I couldn't get over it so I wrote my own function manually parsing a json I pass.

  override fun receiveJson(json: String){
    val gson = Gson()
    val tickerJson: JsonObject = gson.fromJson(json, JsonObject::class.java)
    val resultJson: JsonObject = gson.fromJson(tickerJson.get("result"), JsonObject::class.java)
    bid = resultJson.get("Bid").asDouble
    ask = resultJson.get("Ask").asDouble
  }


来源:https://stackoverflow.com/questions/61333603/why-cant-i-fetch-nested-data-from-json-using-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!