项目作者: aishfenton

项目描述 :
Builds models from JSON Schemas
高级语言: Scala
项目地址: git://github.com/aishfenton/Argus.git
创建时间: 2016-06-29T04:25:37Z
项目社区:https://github.com/aishfenton/Argus

开源协议:MIT License

下载


Argus (船大工)

TravisCI

Scala macros for generating code from Json Schemas. Any structures defined within the
schema (such as properties, enums, etc) are used to generate scala code at compile time. Json encoder/decoders are also generated for the Circe Json library.

NB:
Why Argus? In keeping with the theme of Argonaut and Circe, Argus (son of Arestor) was the builder of the ship “Argo”,
on which the Argonauts sailed.

Quick Example

Starting with this Json schema.

  1. {
  2. "title": "Example Schema",
  3. "type": "object",
  4. "definitions" : {
  5. "Address": {
  6. "type": "object",
  7. "properties": {
  8. "number" : { "type": "integer" },
  9. "street" : { "type": "string" }
  10. }
  11. },
  12. "ErdosNumber": {
  13. "type": "integer"
  14. }
  15. },
  16. "properties": {
  17. "name": {
  18. "type": "array",
  19. "items": { "type": "string" }
  20. },
  21. "age": {
  22. "description": "Age in years",
  23. "type": "integer"
  24. },
  25. "address" : { "$ref" : "#/definitions/Address" },
  26. "erdosNumber" : { "$ref" : "#/definitions/ErdosNumber" }
  27. }
  28. }

We can use the @fromSchemaResource macro to generate case classes for (Root, Address)

  1. import argus.macros._
  2. import io.circe._
  3. import io.circe.syntax._
  4. @fromSchemaResource("/simple.json", name="Person")
  5. object Schema
  6. import Schema._
  7. import Schema.Implicits._
  8. val json = """
  9. |{
  10. | "name" : ["Bob", "Smith"],
  11. | "age" : 26,
  12. | "address" : {
  13. | "number" : 31,
  14. | "street" : "Main St"
  15. | },
  16. | "erdosNumber": 123
  17. |}
  18. """.stripMargin
  19. // Decode into generated case class
  20. val person = parser.decode[Person](json).toOption.get
  21. // Update address
  22. val address = Address(number=Some(42), street=Some("Alt St"))
  23. val newPerson = person.copy(address=Some(address))
  24. // Encode base to json
  25. newPerson.asJson

Many more examples here

Rules

Supported constructs

Object templates (i.e. classes)







JsonGenerated Scala

  1. {
    properties : {
    name : { type : string },
    age : { type : integer }
    },
    required : [“name”]
    }

  1. case class Root(name: String, age: Option[Int] = None)

Basic types














json typejson formatGenerated Scala type
  1. string
  1. String
  1. string
  1. uuid
  1. java.util.UUID
  1. string
  1. date-time
  1. java.time.ZonedDateTime
  1. integer
  1. | int32
  1. Int
  1. integer
  1. int64
  1. Long
  1. integer
  1. int16
  1. Short
  1. integer
  1. int8
  1. Byte
  1. number
  1. | double
  1. Double
  1. number
  1. single
  1. Float
  1. boolean
  1.  
  1. Boolean
  1. null
  1. *
  1. Null

Definitions (i.e. common class definitions)







JsonGenerated Scala

  1. {
    definitions : {
    Person : { },

    }
    properties : {
    person : { $ref : #/definitions/Person” }
    }
    }

  1. case class Person(…)
    case class Root(person: Option[Person] = None)

OneOf (i.e. type A or B)







JsonGenerated Scala

  1. {
    oneOf”: [
    { $ref : #/definitions/Address” },
    { type : number }
    ]
    }

  1. @union sealed trait RootUnion
    case class RootAddress(…) extends RootUnion
    case class RootDouble(…) extends RootUnion

Enums







JsonGenerated Scala

  1. {
    properties”: {
    countries : { enum : [“NZ”, US”, UK”] }
    }
    }

  1. @enum sealed trait Countries
    object CountriesEnum {
    case object NZ(…) extends Countries
    case object US(…) extends Countries

    }
    case class Root(countries: Option[Countries] = None)

Arrays







JsonGenerated Scala

  1. {
    properties”: {
    places : { items : { type”: string } }
    }
    }

  1. case class Root(places: Option[List[String]] = None)

Any Types (i.e. when a field can take arbitrary values)







JsonGenerated Scala

  1. {
    properties”: {
    values : { }
    }
    }

  1. case class Values(x: Any)
    case class Root(values: Option[Values] = None)

Unsupported

  • Only Circe encoders/decoders are supported, although the skeleton is laid out for adding support for other Json libraries.
  • anyOf / allOf. Should be simple to add, just haven’t done it yet.
  • default. Schemas can specify the default value to use for a field. Currently we just ignore these.
  • not. Not sure how you could specify this in a type language. Needs more thoughts
  • additionalProperties, and additionalItems. Json schema lets you specify free-form properties too. These are unsupported
    for now (although I think this should be easy now there’s supprot for Any types)
  • patternProperties. What should be the objects fields in this case? Maybe we just make it a Map?
  • dependencies. Dependencies can also extend the schema… sigh.
  • Any of the validation-only info, such as maxItems, since it doesn’t contribute to the structure.

And lastly: We only generate code from json schemas, but we can’t generate json-schema from code. This is fully possible, but
requires work ;)

There’s still a lot to do! Looking for contributors to address any of above.

Usage Tips

  1. All macros support arguments debug=true and outPath="...". debug causes the generated
    code to be dumped to stdout, and outPath causes the generated code to be written to a file.
    The optional argument outPathPackage allows to specify a package name for the output file.

    1. @fromSchemaResource("/simple.json", debug=true, outPath="/tmp/Simple.Scala", outPathPackage="argus.simple")
    2. object Test
  2. You can generate code from inline json schemas. Also supported are fromSchemaInputStream
    and fromSchemaURL too.

    1. @fromSchemaJson("""
    2. {
    3. "properties" : {
    4. "name" : { "type" : "string" },
    5. "age" : { "type" : "integer" }
    6. },
    7. "required" : ["name"]
    8. }
    9. """)
    10. object Schema
  3. You can name the root class that is generated via the name="..." argument.

    1. @fromSchemaResource("/simple.json", name="Person")
    2. object Schema
    3. import Schema.Person
  4. Within the object we also generate json encoder/decoder implicit variables, but you need to import
    them into scope.

    1. @fromSchemaResource("/simple.json", name="Person")
    2. object Schema
    3. import Schema._
    4. import Schema.Implicits._
    5. Person(...).asJson
  5. You can override specific Encoders/Decoders. All implicits are baked into a trait called LowPriorityImplicits.
    Rather than importing Foo.Implicits you can make your own implicits object that extends this and provides overrides.
    For example:

    1. @fromSchemaResource("/simple.json")
    2. object Foo
    3. import Foo._
    4. object BetterImplicits extends Foo.LowPriorityImplicits {
    5. implicit val myEncoder: Encoder[Foo.Root] = ...
    6. implicit val betterDecoder: Decoder[Foo.Root] = ...
    7. }
    8. import BetterImplicits._
  6. Free form Json (we call them Any types above) are quite common within Json schemas. These are fields that are left open to take any
    kind of Json chunk (maybe for additional properties, or data, etc). Unfortunately they presents a challenge in a strongly typed
    language, such as Scala, where we always need some kind of type.

    The approach we’ve taken is to wrap these chunks in their own case class which has a single field of type Any.
    This also allows you to override the encode/decoders for that type (Root.Data in this example) with something more custom
    if required.

    1. @fromSchemaJson("""
    2. {
    3. "type": "object",
    4. "properties" : {
    5. "data" : { "type": "array", "items": { } }
    6. }
    7. }
    8. """)
    9. object Schema
    10. import Schema._
    11. import Schema.Implicits._
    12. val values = List( Root.Data(Map("size" -> 350, "country" -> "US")), Root.Data(Map("size" -> 350, "country" -> "US")) )
    13. Root(data=Some(values))

    The default encoder/decoder (as shown in the code example above) works if your types are:

    • Primitive types: Boolean, Byte, Short, Int, Long, Float, Double
    • Primate arrays (Array[Byte], Array[Int], etc)
    • Seq[Any] (and subclasses) where Any needs to be one of the types in this list
    • Maps[String, Any], where Any needs to be one of the types in this list.

      Or, in other words, you can’t stick arbitrary objects in the Any wrapper and expect their encoders/decoders to get picked up.
      If you need that then you’ll have to override the default encoder/decoder for this type.