简体   繁体   中英

How to unmarshall JSON object with multiple value types

Say I have an object:

{
  "name": "joe",
  "age": 60
}

How to unmarshall it into a Map[String, String] type?

The JsObject class has a fields parameter that is a Map[String, JsValue] . If you want a Map[String, String] , use mapValues :

import spray.json._
import DefaultJsonProtocol._

val json =
  """{
       "name": "joe",
       "age": 60
     }"""

val jsObj = json.parseJson.asJsObject // JsObject
val myMap: Map[String, String] = jsObj.fields.mapValues(_.toString)

println(myMap)
// Map(name -> "joe", age -> 60)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM