【问题标题】:How to serialize object to AST using json4s?如何使用 json4s 将对象序列化为 AST?
【发布时间】:2014-05-24 10:06:55
【问题描述】:

我正在编写客户序列化程序。在那个序列化器中,我想以某种方式说:“这个东西你已经知道如何序列化了”。

我目前的做法是这样的:

    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)) 的东西既丑陋又低效。如何解决?

【问题讨论】:

    标签: scala json4s


    【解决方案1】:

    您可以调用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))
    

    【讨论】:

    • 很好用!如果您只包含我修改的示例以便使用Extraction.decompose,我会接受这个答案。
    • 能否将您的 Window 类添加到您的问题中?
    • 谁在乎Window 类是什么?
    • 我觉得你很在乎,还是?
    • 请注意,由于 decompose 反映在构造函数上,因此您需要确保非案例类具有完全指定的构造函数,其参数名称与您的字段名称相对应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多