问题
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