Serializing
An object becomes JSON through its annotated properties. Empty values are left out, and every object says what it is.
Model
Mutable classes with @JsonbProperty
Only properties annotated with @JsonbProperty take part. In Scala the annotation must reach the field, hence the @field meta-annotation. DTO marks a class as an object the mapper descends into.
scala
import com.anjunar.json.mapper.provider.DTO
import jakarta.json.bind.annotation.JsonbProperty
import scala.annotation.meta.field
class AddressDto extends DTO {
@(JsonbProperty @field) var city: String = null
@(JsonbProperty @field) var zipCode: String = null
}
class UserDto extends DTO {
@(JsonbProperty @field) var name: String = null
@(JsonbProperty @field) var age: Int = 0
@(JsonbProperty @field) var address: AddressDto = null
@(JsonbProperty @field) var tags: java.util.List[String] = new java.util.ArrayList[String]()
}
Call
serialize with a resolved type
The mapper works on a ResolvedClass from scala-universe, which carries the generic types of collections and maps. The last argument creates helpers such as rules; for plain DTOs it is never called.
scala
import com.anjunar.json.mapper.JsonMapper
import com.anjunar.scala.universe.TypeResolver
val user = new UserDto
user.name = "Patrick"
user.age = 34
user.address = new AddressDto
user.address.city = "Berlin"
user.address.zipCode = "10115"
val json = JsonMapper.serialize(
user,
TypeResolver.resolve(classOf[UserDto]),
null, // no EntityGraph
[T] => (_: Class[T]) => null.asInstanceOf[T] // nothing to inject
)
Output
{"name":"Patrick","age":34,"address":{"city":"Berlin","zipCode":"10115","@type":"AddressDto"},"@type":"UserDto"}
Output
What is written, and what is not
The output is compact and says as little as needed. Read these rules before you rely on a field being present.
Rules
null, empty strings, empty collections and false are left out.
An object without any written property is left out as well.
Every non-empty object gets @type, its simple class name; Hibernate proxy suffixes are removed.
@JsonbProperty("name") renames the field in JSON.
@type is for the reader
Deserialization does not read @type; it always uses the declared type of the property. Clients use it to tell objects apart.