简体   繁体   English

Scala将Json播放到OrderdMap

[英]Scala Play Json to OrderdMap

I'm new to scala. 我是斯卡拉的新手。 I'm trying to convert JSON to ordered Map which should have values in insertion order. 我正在尝试将JSON转换为有序的Map,它应该具有插入顺序的值。 But compiler says I can convert only to Map, not to ListMap and asking me to implement an implicit Read or format. 但编译器说我只能转换为Map,而不能转换为ListMap,并要求我实现隐式Read或格式。

But I wanted to know is there any way we can directly use some existing functions as we have for JSON to Map conversion? 但我想知道有没有什么方法可以直接使用一些现有函数,因为我们有JSON到Map转换? I also checked for an option in SprayJson and other, but it looks like there are no existing functions available for JSON to ordered collection. 我还检查了SprayJson和其他的选项,但看起来没有现有的JSON函数可用于有序集合。

 import play.api.libs.json._
 import scala.collection.immutable.ListMap

object Test extends App{

 val jsonString = """{"ONE":"O", "TWO":"T", "THREE":"T", "FOUR":"F", "FIVE":"F"}"""
val jsonValue = Json.parse(jsonString).as[ListMap[String, String]]

 println("Result : " + jsonValue)
}

Expected Result ListMap(ONE -> O, TWO -> T, THREE -> T, FOUR -> F, FIVE -> F); 

The keys of the Json object is not ordered and Hence the keys, values of Json object can be retrived at any order and hence it is not guaranteed to be ordered. Json对象的键不是有序的,因此Json对象的键,值可以按任何顺序重新获得,因此不能保证订购。 Ordering is maintained only in arrays not in objects. 仅在不在对象中的数组中维护排序。 so you will have to change the Json object to an Json array to achieve this like shown below 因此,您必须将Json对象更改为Json数组才能实现此目的,如下所示

scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap

scala> import play.api.libs.json._
import play.api.libs.json._

scala> val jsonString = """[{"F1":{"A" : "a"}}, {"F2":{"B" : "b"}}, {"F3":{"C" : "c"}}, {"F4":{"D" : "d"}}, {"F5":{"E" : "e"}}]"""
jsonString: String = [{"F1":{"A" : "a"}}, {"F2":{"B" : "b"}}, {"F3":{"C" : "c"}}, {"F4":{"D" : "d"}}, {"F5":{"E" : "e"}}]

scala> val list = Json.parse(jsonString).as[List[Map[String, Map[String, String]]]].flatten.foldLeft(ListMap[String,Map[String, String]]())({ case (arr,(key, value)) => arr + (key -> value)})
list: scala.collection.immutable.ListMap[String,Map[String,String]] = Map(F1 -> Map(A -> a), F2 -> Map(B -> b), F3 -> Map(C -> c), F4 -> Map(D -> d), F5 -> Map(E -> e))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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