Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

Adds @JsonProperty getter support in case classes #69

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import java.lang.reflect.Modifier
import com.codahale.jerkson.JsonSnakeCase
import com.codahale.jerkson.Util._
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.annotation.{JsonIgnore, JsonIgnoreProperties}
import com.fasterxml.jackson.annotation.{JsonIgnore, JsonIgnoreProperties, JsonProperty}
import com.fasterxml.jackson.databind.{SerializerProvider, JsonSerializer}

class CaseClassSerializer[A <: Product](klass: Class[_]) extends JsonSerializer[A] {
Expand All @@ -23,12 +23,17 @@ class CaseClassSerializer[A <: Product](klass: Class[_]) extends JsonSerializer[
private val methods = klass.getDeclaredMethods
.filter { _.getParameterTypes.isEmpty }
.map { m => m.getName -> m }.toMap

private val jsonGetters = methods
.filter { _._2.getAnnotation(classOf[JsonProperty]) != null }
.map { m => m._2.getAnnotation(classOf[JsonProperty]).value -> m._2 }.toMap

def serialize(value: A, json: JsonGenerator, provider: SerializerProvider) {
json.writeStartObject()
for (field <- nonIgnoredFields) {
val methodOpt = methods.get(field.getName)
val fieldValue: Object = methodOpt.map { _.invoke(value) }.getOrElse(field.get(value))
val getterOpt = jsonGetters.get(field.getName)
val fieldValue: Object = getterOpt.map { _.invoke(value) }.getOrElse(methodOpt.map { _.invoke(value) }.getOrElse(field.get(value)))
if (fieldValue != None) {
val fieldName = methodOpt.map { _.getName }.getOrElse(field.getName)
provider.defaultSerializeField(if (isSnakeCase) snakeCase(fieldName) else fieldName, fieldValue, json)
Expand Down