2014-04-10 3 views
13

मैं एक ग्राहक सीरिएलाइज़र लिख रहा हूं। उस Serializer में मैं किसी भी तरह से कहना चाहूंगा: "और यह बात आप पहले ही जानते हैं कि serialize कैसे करें"।json4s का उपयोग कर एएसटी पर ऑब्जेक्ट को क्रमबद्ध करने के लिए कैसे?

मेरे वर्तमान दृष्टिकोण है कि तरह लग रहा है:

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))) 
     })) 

parse(write(frame)) यही बातें दोनों बदसूरत और अक्षम है। इसे कैसे ठीक करें?

उत्तर

23

आप Extraction.decompose(a: Any)(implicit formats: Formats): JValue जो कुछ क्रम प्रतिबिंब का उपयोग मूल्य से एक JValue पैदा करता है कह सकते हैं।

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

अच्छा लग रहा है! मैं कल कोशिश करूँगा। – mjaskowski

+0

महान काम करता है! मैं इस जवाब को स्वीकार करता है, तो आप केवल अपने उदाहरण संशोधित इतना है कि 'Extraction.decompose' प्रयोग किया जाता है शामिल करेंगे। – mjaskowski

+0

क्या आप अपनी विंडो कक्षा को अपने प्रश्न में जोड़ सकते हैं? –

संबंधित मुद्दे