简体   繁体   中英

Scala + Play: serialize Map to Json Array

Imagine you have a Map[String, List[String]] that looks like this:

val myMap = Map(
   "ab" -> List("yo", "yo2", "yo3"),
   "cd" -> List("hi", "hi1", "hi2")
 )

if we do Json.toJson(myMap), the resulting JSON is

 {
   "ab" : ["yo", "yo2", "yo3"],
   "cd" : ["hi", "hi1", "hi2"]
 }

Is there a way we could get the outer container to be an array instead of an object? Like

 [
   "ab" : ["yo", "yo2", "yo3"],
   "cd" : ["hi", "hi1", "hi2"]
 ]

I'm not sure that this would be valid Json. Thanks.

The last one is not valid JSON. You could use Json.toJson(myMap.toList) to obtain result as @Tyth has answered. Actually Map is similar to Object of JSON format, cause it provides extracting values by key. In case with Array , it's reached over iterate over each element.

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