2016-05-21 28 views
0

Ich versuche, JSON String mit Scala und playframework zu analysieren, ich habe doc gelesen, aber immer noch bin ich fest. Ich habe:Parsing JSON in Scala, die Karte enthält

val jsonStr = """{ 
      | "metric": "java.lang.Memory.HeapMemoryUsage.committed", 
      | "tags": { 
      |  "instanceId": "ubuntu", 
      |  "runId": "B_name_of_the_app-c4m8_0_2016-01-01_23-31-34" 
      | }, 
      | "aggregateTags": [], 
      | "dps": { 
      |  "1455711498": 8.71890944E8, 
      |  "1455711558": 9.10688256E8, 
      |  "1455711618": 9.24319744E8, 
      |  "1455711678": 8.47773696E8, 
      |  "1455711738": 9.35329792E8, 
      |  "1455711798": 9.53679872E8, 
      |  "1455714981": 1.983905792E9, 
      |  "1455715041": 2.054684672E9, 
      |  "1455715101": 2.05520896E9 
      | } 
      | }""".stripMargin 

nach playframework doc I-Klassen erstellt, diese Sache zu analysieren:

// Beginn der scala Datei

import play.api.libs.json.{JsPath, Json, Reads} 
import play.api.libs.functional.syntax._ 

case class Metric(metricName: String, tags: Tags, aggregateTags: Option[Seq[String]], dps: Seq[Map[String,Double]]) 

object Metric{ 

implicit val metricReads: Reads[Metric] = (
(JsPath \ "metric").read[String] and 
    (JsPath \ "tags").read[Tags] and 
    (JsPath \ "aggreagateTags").readNullable[Seq[String]] and 
    (JsPath \ "dps").read[Seq[Map[String,Double]]] //this one is tricky 
)(Metric.apply _) 
} 

case class Tags(instanceId:String, runId: String) 

object Tags{ 
implicit val tagsReads: Reads[Tags] = (
(JsPath \ "instanceId").read[String] and (JsPath \ "runId").read[String] 
)(Tags.apply _) 
} 

Json.parse(jsonStr).validate[Metric] 

// Ende der scala Datei Leider Validierungsergebnisse mit:

res0: play.api.libs.json.JsResult[Metric] = JsError(List((//dps,List(ValidationError(List(error.expected.jsarray),WrappedArray()))))) 

Ich bin mir nicht sicher, wie man dieses Problem löst, versuchte parse dps auch als eine getrennte Klasse, aber auch nicht funktioniert .. Irgendwelche Tipps?

Antwort

2

Sie haben (JsPath \ "dps").read[Seq[Map[String,Double]]] aber dps in Ihrem JSON ist kein Seq aber ein einzelner Eintrag -, dass ein Teil des Lesers zu (JsPath \ "dps").read[Map[String,Double]] Ändern wird das Problem beheben.