使用Scala将List转换为Play框架中的特定JSON格式

时间:2014-03-12 20:51:42

标签: json scala playframework

我有一个类型列表,其中包含三个字段(服务,总计,改进)。当我使用Json.toJson(myList)将其转换为JSON时,我得到了以下格式的JSON:

  [
  {
     "services":"S4",
     "total":1,
     "improved":1
  },
  {
     "services":"S1",
     "total":2,
     "improved":1
  },
  {
     "services":"S2",
     "total":3,
     "improved":2
  }
  ]

在Scala的Play 2.x中使用JSON库,如何以下面的JSON格式转换myList?

[
 {
   "key" : "total",
   "values" :[
      {
      "services" : "s1",
      "value" : 2
      },
      "services" : "s2",
      "value" : 3
      {
      "services" : "s4",
      "value" : 1
      }
    ]
 }, 
 {
   "key" : "improved",
   "values" :[
      {
      "services" : "s1",
      "value" : 1
      },
      "services" : "s2",
      "value" : 2
      {
      "services" : "s4",
      "value" : 1
      }
    ]
 }
 ]

提前致谢。

2 个答案:

答案 0 :(得分:0)

由于您已经在处理OO,我认为您可以将List包装到更具体的对象中并将其转换为JSON:

case class Foo(services: String, total: Int, improved: Int)

case class B(key: String, value: Int)
case class A(key: String, values: Seq[B] = Seq())

val myOriginalList = Seq(Foo("S4", 1, 1), Foo("S1", 2, 1), Foo("S2", 3, 2))

val transformedList = myOriginalList.foldLeft((A("total"), A("improved")))({ (res, x) =>
    (res._1.copy(values = B(x.services, x.total) +: res._1.values),
    res._2.copy(values = B(x.services, x.improved) +: res._2.values))
}).map({x => List(x._1, x._2)})

Json.toJson(transformedList)

使用此解决方案的问题之一(或可能不是)是您无法动态解析Foo属性。

你也可以试试Json变形金刚:http://www.playframework.com/documentation/2.2.x/ScalaJsonTransformers

答案 1 :(得分:0)

这是一个Scala新手的解决方案(我确定它不优雅): 我正在使用此处提供的解决方案:http://www.playframework.com/documentation/2.1.1/ScalaJson

 //some data
 case class PatientAggregateValues(total: Int, improved: Int)
 val scoreMap = Map.empty[String, PatientAggregateValues]
 scoreMap += ("S1" -> PatientAggregateValues(2, 1))
 scoreMap += ("S2" -> PatientAggregateValues(3, 2))
 scoreMap += ("S4" -> PatientAggregateValues(1, 1))

      //main logic
 val totalMap = scoreMap map { case (k,v) => Json.toJson(scala.collection.immutable.Map("service" -> Json.toJson(k), "value" -> Json.toJson(v.total))) } toSeq

 val improvedMap = scoreMap map { case (k,v) => Json.toJson(scala.collection.immutable.Map("service" -> Json.toJson(k), "value" -> Json.toJson(v.improved))) } toSeq

 Json.toJson(scala.collection.immutable.Map("total" -> totalMap, "improved" -> improvedMap))

感谢。