JSON 編碼器生成 

JsonCodecPlugin 新增至子專案將會為違禁品類型生成 sjson-new JSON 程式碼。

lazy val root = (project in file(".")).
  enablePlugins(ContrabandPlugin, JsonCodecPlugin).
  settings(
    scalaVersion := "2.11.8",
    libraryDependencies += "com.eed3si9n" %% "sjson-new-scalajson" % contrabandSjsonNewVersion.value
  )

sjson-new 是一個編碼器工具組,可讓您定義支援 Spray JSON 的 AST、SLIP-28 Scala JSON 和 MessagePack 作為後端的程式碼。

編碼器的套件名稱可以使用 @codecPackage 指令指定。

package com.example
@target(Scala)
@codecPackage("com.example.codec")
@codecTypeField("type")
@fullCodec("CustomJsonProtocol")

type Person {
  name: String!
  age: Int
}

JsonFormat 特徵將會在 com.example.codec 套件下生成,同時也會生成一個名為 CustomJsonProtocol 的完整編碼器,它混合了所有特徵。

以下說明如何使用生成的 JSON 編碼器

scala> import sjsonnew.support.scalajson.unsafe.{ Converter, CompactPrinter, Parser }
import sjsonnew.support.scalajson.unsafe.{Converter, CompactPrinter, Parser}

scala> import com.example.codec.CustomJsonProtocol._
import com.example.codec.CustomJsonProtocol._

scala> import com.example.Person
import com.example.Person

scala> val p = Person("Bob", 20)
p: com.example.Person = Person(Bob, 20)

scala> val j = Converter.toJsonUnsafe(p)
j: scala.json.ast.unsafe.JValue = JObject([Lscala.json.ast.unsafe.JField;@6731ad72)

scala> val s = CompactPrinter(j)
s: String = {"name":"Bob","age":20}

scala> val x = Parser.parseUnsafe(s)
x: scala.json.ast.unsafe.JValue = JObject([Lscala.json.ast.unsafe.JField;@7331f7f8)

scala> val q = Converter.fromJsonUnsafe[Person](x)
q: com.example.Person = Person(Bob, 20)

scala> assert(p == q)

跳過編碼器生成 

使用 @generateCodec(false) 注解來跳過某些類型的編碼器生成。

interface MiddleInterface implements InterfaceExample
@generateCodec(false)
{
  field: Int
}