Home > front end >  How do I de-serialize this json?
How do I de-serialize this json?

Time:01-04

I am working on a project where I need to access currency rates once a day so I am trying to use this json.

To read this, I am simply getting the text of the URL and then trying to use the JSONReader to de-serialize.

 val url = URL("https://www.floatrates.com/daily/usd.json")
        val stream = url.openStream()
        url.readText()

        val jsonReader = JsonReader(InputStreamReader(stream))
        jsonReader.isLenient = true

        jsonReader.beginObject()
        while (jsonReader.hasNext()) {
            val codeName:String = jsonReader.nextName()
            jsonReader.beginObject();
            var code:String? = null
            var rate = 0.0
            while (jsonReader.hasNext()) {
                val name:String = jsonReader.nextName()
                when(name){
                    "code" -> {
                        code = jsonReader.nextString()
                        break
                    }
                    "rate" -> {
                        rate = jsonReader.nextDouble()
                        break
                    }
                    else -> {
                        jsonReader.skipValue()
                    }
                }

                code?.let {
                    rates?.set(it, rate)
                }
            }
        }
            jsonReader.endObject();

When I run the code , I get:

 Expected BEGIN_OBJECT but was STRING

at

jsonReader.beginObject();

When I try using Gson, with the code below:

var url = URL("https://www.floatrates.com/daily/usd.json").readText()
//url = "[${url.substring(1, url.length - 1)}]"
val gson = Gson()
val currencies:Array<SpesaCurrency> = gson.fromJson(url, Array<SpesaCurrency>::class.java)

I get this error :

Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $[0]

at:

gson.fromJson(url, Array<SpesaCurrency>::class.java)

SpesaCurrency.kt looks like this:

class SpesaCurrency(
  val code:String,
  val alphaCode:String,
  val numericCode:String,
  val name:String,
  val rate:Float,
  val date:String,
  val inverseRate:Float
)

Any help is greatly appreciated.

CodePudding user response:

I think there is one

jsonReader.endObject();

missing in your code. That imbalance causes the program to fail after the first object has been read. Add it after the inner

while (jsonReader.hasNext()) {
   ...
}

loop.

  •  Tags:  
  • Related