2014-04-10 8 views
13

Ich schreibe einen Customer Serializer. In diesem Serialisierer möchte ich irgendwie sagen: "und dieses Ding, das Sie bereits wissen, wie man serialisiert".Wie Objekt mit json4s zu AST zu serialisieren?

Mein aktueller Ansatz sieht so aus:

import org.json4s.native.Serialization._ 
    import org.json4s.JsonDSL.WithBigDecimal._ 

    object WindowSerializer extends CustomSerializer[Window](format => 
     ([omitted], 
     { 
      case Window(frame, size) => 

      ("size" -> size) ~ 
      ("frame" -> parse(write(frame))) 
     })) 

Das parse(write(frame)) Dinge ist sowohl hässlich und ineffizient. Wie behebt man das?

Antwort

23

Sie können Extraction.decompose(a: Any)(implicit formats: Formats): JValue anrufen, die eine JValue von einem Wert mit Laufzeit-Reflektion produziert.

import org.json4s._ 
import org.json4s.jackson.JsonMethods._ 
import org.json4s.JsonDSL._ 
import java.util.UUID 

case class Thing(name: String) 
case class Box(id: String, thing: Thing) 

class BoxSerializer extends CustomSerializer[Box](format => ({ 
    case jv: JValue => 
    val id = (jv \ "id").extract[String] 
    val thing = (jv \ "thing").extract[Thing] 
    Box(id, thing) 
}, { 
    case b: Box => 
    ("token" -> UUID.randomUUID().toString()) ~ 
     ("id" -> box.id) ~ 
     ("thing" -> Extraction.decompose(box.thing)) 
})) 

implicit val formats = DefaultFormats + new BoxSerializer 

val box = Box("1000", Thing("a thing")) 

// decompose the value to JSON 
val json = Extraction.decompose(box) 
println(pretty(json)) 
// { 
// "token" : "d9bd49dc-11b4-4380-ab10-f6df005a384c", 
// "id" : "1000", 
// "thing" : { 
//  "name" : "a thing" 
// } 
// } 

// and read a value of type Box back from the JSON 
println(json.extract[Box]) 
// Box(1000,Thing(a thing)) 
+0

Sieht gut aus! Ich werde es morgen versuchen. – mjaskowski

+0

Großartig, das funktioniert! Ich werde diese Antwort akzeptieren, wenn Sie nur mein Beispiel so geändert, dass 'Extraction.decompose' verwendet wird. – mjaskowski

+0

Könnten Sie Ihre Window-Klasse zu Ihrer Frage hinzufügen? –

Verwandte Themen