GithubHelp home page GithubHelp logo

pushka's Introduction

Pushka

Build Status

Pushka is a pickler implemented without any runtime reflection. It created to reach well human readability of output JSON and good performance. Pushka works well both on Scala and Scala.js.

Motivation

  1. Most of picklers are writes case classes "as is". For example if we have Option value it will be writeen with some kind of wrapper. In the case of sealed traits, most picklers writes metadata: trait name and case class name. This make JSON unreadable by human and make it usless for creating public API. We want to achive high human readablility of output JSON: no wrappers if it possible, no metadata ever.

  2. Codebase simplicity. In our work we encountered that some picklers based on implicit macros (including shapeless base picklers) are fails on our data. In this project we want make code as simple as possible to find bugs faster.

  3. High performance. Minimum runtime overhead. See Boopickle benchmarks.

Usage

Add Pushka dependency to your project.

// For Scala.js
libraryDependencies += "com.github.fomkin" %%% "pushka-json" % "0.4.1"

// For Scala.jvm
libraryDependencies += "com.github.fomkin" %% "pushka-json" % "0.4.1"

Pushka uses marco annotations which implemented in macro paradise plugin. Unfortunately it can't be added transitively by Pushka dependency, so you need to plug it manually.

addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0-M5" cross CrossVersion.full)

Let define types we want to write to JSON.

import pushka.annotation._

@pushka 
case class User(email: String, name: Option[String], role: Role)

@puska
sealed trait Role

object Role {

  case object Moderator extends Role
  
  case object Accountant extends Role
  
  case class Group(xs: Seq[Role]) extends Role
}

Ok. Now let create data and write it to JSON

import pushka.json._

val data = User(
  email = "[email protected]", 
  name = None, 
  role = Role.Accountant
)

println(write(data))
{
  "email": "[email protected]",
  "role": "accountant"
}

Ok. Change users role.

data.copy(role = Role.Group(Role.Accountant, Role.Moderator))
{
  "email": "[email protected]",
  "role": {
    "group": ["accountant", "moderator"]
  }  
}

Add user name.

data.copy(name = Some("Jonh Doe"))
{
  "email": "[email protected]",
  "name": "John Doe",
  "role": {
    "group": ["accountant", "moderator"]
  }  
}

Now, in the opposite direction. Lets read JSON.

val json = """
  {
    "email": "[email protected]",
    "name": "John Doe",
    "role": {
      "group": ["accountant", "moderator"]
    }  
  }
"""

assert {
  read[User](json) == User(
    email = "[email protected]", 
    name = Some("Jonh Doe"), 
    role = Role.Group(Role.Accountant, Role.Moderator)
  )
}    

Case class default parameters

That if we add new field to class and try to read JSON written to KV storage with an old version of the class? An exception will be thrown. To avoid this behavior add new filed with default value.

@pushka 
case class User(
  email: String, 
  name: Option[String], 
  role: Role, 
  photoUrl: String = "http://example.com/images/users/dafault.jpg"
)

@key annotation

Pushka allows to define the key that a field is serialized with via a @key annotation

@pushka
case class Log(@key("@ts") timestamp: String, message: String)

Custom readers and writers

Sometimes we want to write objects in a special way.

import pushka.RW
import pushka.Ast

case class Name(first: String, last: String)

object Name {
  val Pattern = "(.*) (.*)".r
  implicit val rw = new pushka.RW[Name] {
    def write(value: Name): Ast = {
      Ast.Str(s"${value.first} ${value.last}")
    }
    def read(ast: Ast): Name = ast match {
      case Ast.Str(Pattern(first, last)) => Name(first, last)
      case _ => throw new Exception("It's wrong!")  
    }
  }
}

// ...

write(User("John", "Doe"))
"John Doe"

Write None as null

You can configure Pushka to write None explictly.

@pushka 
case class User(email: String, name: Option[String])

implicit val config = pushka.Config(leanOptions = false)
write(User("[email protected]", None))
{ "email": "[email protected]", "name": null }

License

Code released under Apache 2.0 license. See LICENSE.

pushka's People

Contributors

fomkin avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.