Last active
March 19, 2019 03:17
-
-
Save haiphucnguyen/7a8181fe93b739a3d862e90cc64f8ad0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycollab.billing.fastspring | |
import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty} | |
import com.fasterxml.jackson.core.{JsonGenerator, JsonParser} | |
import com.fasterxml.jackson.databind._ | |
import com.fasterxml.jackson.databind.annotation.{JsonDeserialize, JsonSerialize} | |
import com.fasterxml.jackson.databind.module.SimpleModule | |
import org.joda.time.LocalDateTime | |
import org.joda.time.format.DateTimeFormat | |
import scala.beans.BeanProperty | |
object JacksonSample { | |
def main(args: Array[String]): Unit = { | |
val mapper = new ObjectMapper() | |
//Serialize object to JSON | |
val json = mapper.writeValueAsString(new Student("Nguyen", "Hai", Array( | |
new Classroom("class 1", new LocalDateTime(2016, 1, 1, 9, 0)), | |
new Classroom("class 2", new LocalDateTime(2016, 1, 1, 11, 0))))) | |
Console.println("Json: " + json) | |
//De-serialize JSON to object | |
val person = mapper.readValue(json, classOf[Student]) | |
} | |
} | |
@JsonCreator | |
class Student(@JsonProperty("firstName") @BeanProperty val firstName: String, | |
@JsonProperty("lastName") @BeanProperty val lastName: String, | |
@JsonProperty("address") @BeanProperty val address: Array[Classroom]) { | |
} | |
@JsonCreator | |
@JsonSerialize(using = classOf[ClassroomSerializer]) | |
@JsonDeserialize(using = classOf[ClassroomDeserializer]) | |
class Classroom(@JsonProperty("name") @BeanProperty var name: String, | |
@JsonProperty("time") @BeanProperty var time: LocalDateTime) { | |
} | |
class ClassroomSerializer extends JsonSerializer[Classroom] { | |
private val formatter = DateTimeFormat.forPattern("dd-MMM-yyyy") | |
override def serialize(value: Classroom, gen: JsonGenerator, serializers: SerializerProvider): Unit = { | |
gen.writeStartObject | |
gen.writeStringField("name", value.name) | |
gen.writeStringField("time", formatter.print(value.time)) | |
gen.writeEndObject | |
} | |
} | |
class ClassroomDeserializer extends JsonDeserializer[Classroom] { | |
private val formatter = DateTimeFormat.forPattern("dd-MMM-yyyy") | |
override def deserialize(p: JsonParser, ctxt: DeserializationContext): Classroom = { | |
val node: JsonNode = p.getCodec.readTree(p) | |
val classroom = new Classroom("", null) | |
classroom.name = node.get("name").asText() | |
classroom.time = LocalDateTime.parse(node.get("time").asText(), formatter) | |
classroom | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment