I read a JSON file and use json4s to parse JSON.
How I can sort an array of JObject that I read from the file?
package org.example
import org.json4s._
import org.json4s.native.JsonMethods._
object Main extends App {
val file = scala.io.Source.fromURL("https://raw.githubusercontent.com/mledoze/countries/master/countries.json")
val text = file.mkString
val json = parse(text)
val countries = json.children
countries.sortBy(...)
}
Each country has a field "area" and I need to sort the list by this field. I don't know how to use sortBy in this situation because the country is not just an object of some class. This is JObject and the field "area" has a type JInt.
Can you help me? Or maybe do you know other solution?
Thanks, Gaël J for Hint.
I solved my problem as follows:
package org.example
import org.json4s._
import org.json4s.native.JsonMethods._
object Main extends App {
val file = scala.io.Source.fromURL("https://raw.githubusercontent.com/mledoze/countries/master/countries.json")
val text = file.mkString
val json = parse(text)
val countries = json.children
val countriesSorted = countries.sortWith((x: JValue, y: JValue) => {
//File has a few countries with area that has type of Double
def getValue(value: JValue): Double = {
value \ "area" match {
case JDouble(value) => value
case JInt(value) => value.toDouble
case _ => 0
}
}
val xValue = getValue(x)
val yValue = getValue(y)
xValue > yValue
})
for (country <- countriesSorted)
println(country \ "area")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.