简体   繁体   English

通过scala-pickling序列化后从json中删除tpe

[英]remove tpe from json after serialization via scala-pickling

Is there an easy way to serialize to json without "tpe" field inside an object? 有没有一种简单的方法可以序列化为json,而对象内部没有“ tpe”字段? I need to serialize case classes to json structures and then, send them over the wire (They won't been deserialized in future). 我需要将案例类序列化为json结构,然后通过电线发送它们(以后将不会反序列化它们)。 I have a specific api, so.. I don't need additional fields. 我有一个特定的api,所以..我不需要其他字段。

For class Person illustrated below: 对于下图所示的Person

case class Person(Name: String, Age: int, CandyLover: Boolean)

I'd like to see following: 我想看看以下内容:

{
  "Name": "Paul",
  "Age": 23,
  "CandyLover": true
}

I would suggest you to take a look at spray-json or argonaut. 我建议您看一看Spray-json或argonaut。 Or play-json if you are already using Play. 或play-json(如果您已经在使用Play)。

Scala pickling is not really a json library, it was not created to generate JSON for public API, it's not flexible, you can't define JSON protocol first and then provide pickling serialization to match protocol. Scala酸洗并不是真正的json库,它不是为公共API生成JSON而创建的,它不灵活,您不能先定义JSON协议,然后再提供酸洗序列化以匹配协议。 Pickling is for computer-to-computer serialization where no one is really care about bytes going between apps. 酸洗用于计算机到计算机的序列化,其中没有人真正关心应用之间的字节数。

Probably the simplest way to do it is to pass somehow the Hint into JSONPickleBuilder . 可能最简单的方法是将Hint某种方式传递给JSONPickleBuilder Quick way to do it is to override builders in JSONPickleFormat by calling hintStaticallyElidedType() method from PickleTools . 快速的方法是通过从PickleTools调用hintStaticallyElidedType()方法来覆盖JSONPickleFormat的构建器。

Here is kind of code snippet to demonstrate it: 这是一种代码片段来演示它:

import org.specs2.matcher.JsonMatchers
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.pickling.Defaults._
import scala.pickling.json.{JSONPickleBuilder, JSONPickleFormat, JsonFormats}
import scala.pickling.{Output, PBuilder, PickleTools, StringOutput}

class PersonJsonFormatsTest extends Specification with JsonMatchers {
  trait Context extends Scope with PersonJsonFormats

  trait PersonJsonFormats extends JsonFormats {
    override implicit val pickleFormat: JSONPickleFormat = new PersonJSONPickleFormat
  }

  class PersonJSONPickleFormat extends JSONPickleFormat {
    override def createBuilder() = new JSONPickleBuilder(this, new StringOutput) with PickleTools {
      hintStaticallyElidedType()
    }
    override def createBuilder(out: Output[String]): PBuilder = new JSONPickleBuilder(this, out) with PickleTools {
      hintStaticallyElidedType()
    }
  }

  "Pickle" should {
    "Serialize Person without $type field in resulting JSON" in new Context {
      case class Person(Name: String, Age: Int, CandyLover: Boolean)

      val pickledPersonObject = Person("Paul", 23, CandyLover = true).pickle
      println(pickledPersonObject.value)
      pickledPersonObject.value must not */("$type" → ".*".r)
    }
  }
}

The output of println(pickledPersonObject.value) will be as you need: println(pickledPersonObject.value)的输出将如您println(pickledPersonObject.value)

{
  "Name": "Paul",
  "Age": 23,
  "CandyLover": true
}

This way you will stay aligned with further pickle updates. 这样,您将与进一步的泡菜更新保持一致。

PS If someone knows more elegant and convenient way to reach the same behaviour - please let us know :-) PS:如果有人知道达到相同行为的更优雅,更便捷的方法,请告诉我们:-)

For scala-pickling 0.10.x: 对于scala-pickling 0.10.x:

import scala.pickling._
import scala.pickling.json.{JSONPickle, JSONPickleBuilder, JSONPickleFormat, JsonFormats}
import scala.pickling.pickler.AllPicklers

object serialization extends JsonFormats with Ops with AllPicklers {
  override implicit val pickleFormat: JSONPickleFormat = new JSONPickleFormat {

    private def setHints(h: Hintable): Unit = {
      h.hintStaticallyElidedType()
      h.hintDynamicallyElidedType()
    }

    override def createBuilder(): JSONPickleBuilder = {
      val builder = super.createBuilder()
      setHints(builder)
      builder
    }

    override def createBuilder(out: Output[String]): PBuilder = {
      val builder = super.createBuilder(out)
      setHints(builder)
      builder
    }

    override def createReader(pickle: JSONPickle): PReader = {
      val reader = super.createReader(pickle)
      setHints(reader)
      reader
    }
  }
}

object SerializationTest extends App {
  import serialization._

  case class Person(firstName: String, lastName: String)

  val pickle: JSONPickle = Person("Evelyn", "Patterson").pickle
  val jsonString: String = pickle.value // {"firstName": "Evelyn","lastName": "Patterson"}

  val person: Person = jsonString.unpickle[Person]
}

For scala-pickling 0.11.x: 对于scala-pickling 0.11.x:

import scala.pickling._
import scala.pickling.json.{JSONPickle, JSONPickleBuilder, JSONPickleFormat}
import scala.pickling.pickler.AllPicklers

object serialization extends AllPicklers {

  private final class CustomJSONPickleFormat(tag: FastTypeTag[_]) extends JSONPickleFormat {

    private def setHints(h: Hintable) {
      h.hintElidedType(tag)
    }

    override def createBuilder(): JSONPickleBuilder = {
      val b = super.createBuilder()
      setHints(b)
      b
    }
    override def createBuilder(out: Output[String]): PBuilder = {
      val b = super.createBuilder(out)
      setHints(b)
      b
    }
    override def createReader(pickle: JSONPickle): PReader = {
      val b = super.createReader(pickle)
      setHints(b)
      b
    }
  }

  implicit val staticOnly = static.StaticOnly // for compile time serialization methods generation

  implicit final class EncodeDecodeOps[T](picklee: T) {
    def encode(implicit pickler: Pickler[T]): String = {
      val pickleFormat = new CustomJSONPickleFormat(pickler.tag)
      functions.pickle(picklee)(pickleFormat, pickler).value
    }

    def decode[A](implicit c: T => String, unpickler: Unpickler[A]): A = {
      val pickleFormat = new CustomJSONPickleFormat(unpickler.tag)
      functions.unpickle[A](json.JSONPickle(picklee))(unpickler, pickleFormat)
    }
  }
}

case class Person(firstName: String, lastName: String) {
   @transient var x = "test"
}

object SerializationTest extends App {
  import serialization._

  val jsonString = Person("Lisa", "Daniels").encode

  println(jsonString)

  val person = jsonString.decode[Person]

  println(person)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM