My motivation to build this library is because I didn't find a great library for JSON Serialization in Scala as ActiveModel::Serializer or fast_jsonapi so I thought, why not to build a pretty DSL for JSON Serialization in this great language?
Built with ❤︎ by jdavierb
- ❤️ DSL similar to Active Model Serializer, Netflix Fast JSON API
- ✅ Support encoders for JSON Serialization like Circle, Spray
- 👋 Easy to test
If you use SBT you can add ditto-serializer in your project with
externalResolvers += "ditto-serializer" at "https://maven.pkg.github.com/jdaviderb/ditto-serializer"
libraryDependencies += "jdaviderb" %% "ditto-serializer" % "0.5"
Ditto serializer is very simple we only have 3 helpers in our API for build JSON
- attribute[T]: this helper append to field to the JSON Object
- list: this helper returns a new instance of DittoList (Array) you can add new a element using the method
add
example:list.add("new item")
- map: this helper returns a new instance of DittoMap [JsonObject] you can add a new (key, value) using the method
set
example:map.set("key", "value")
case class User(firstName: String, lastName: String)
import org.jdaviderb.dittoSerializer.core.Serializer
class UserSerializer(val user: User) extends Serializer {
attribute("name") { user.firstName }
attribute("last_name") { user.lastName }
attribute("full_name") { s"${user.firstName} ${user.lastName}" }
}
if you want to use Circle for JSON Serialization, you have to add this package in your project
externalResolvers += "ditto-circle" at "https://maven.pkg.github.com/jdaviderb/ditto-circle"
libraryDependencies += "jdaviderb" %% "ditto-circle" % "0.5"
Example:
import org.jdaviderb.DittoCircle.Enconder
import org.jdaviderb.dittoSerializer.core.Serializer
// Model definition
case class User(firstName: String, lastName: String)
// Serializer
class UserSerializer(val user: User) extends Serializer {
attribute("name") { user.firstName }
attribute("last_name") { user.lastName }
attribute("full_name") { s"${user.firstName} ${user.lastName}" }
}
// JSON Serialization
val jorge = User("Jorge", "Hernandez")
val josue = User("Josue", "Hernandez")
val users = List(jorge, josue)
Enconder.from(new UserSerializer(jorge))
/*
RESULT:
{
"full_name" : "Jorge Hernandez",
"last_name" : "Hernandez",
"name" : "Jorge"
}
*/
Enconder.fromList(users.map(new UserSerializer(_)))
/*
RESULT:
[
{
"full_name" : "Jorge Hernandez",
"last_name" : "Hernandez",
"name" : "Jorge"
},
{
"full_name" : "Josue Hernandez",
"last_name" : "Hernandez",
"name" : "Josue"
}
]
*/
Pending
Pending
- add more documentation
- add examples for tests
- support Json4s
- support Spray Json