Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonIgnore serialising Scala case class property using Jackon and Json4s

I'm trying to prevent one of the properties of a Scala case class being serialised. I've tried annotating the property in question with the usual @JsonIgnore and I've also tried attaching the @JsonIgnoreProperties(Array("property_name")) to the case class. Neither of which seem to achieve what I want.

Here's a small example:

import org.json4s._
import org.json4s.jackson._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.{read, write}
import com.fasterxml.jackson.annotation._

object Example extends App {

    @JsonIgnoreProperties(Array("b"))
    case class Message(a: String, @JsonIgnore b: String)

    implicit val formats = Serialization.formats(NoTypeHints)
    val jsonInput = """{ "a": "Hello", "b":"World!" }"""
    val message = read[Message](jsonInput)
    println("Read " + message) // "Read Message(Hello,World!)

    val output = write(message) 
    println("Wrote " + output) // "Wrote {"a":"Hello","b":"World!"}"
}
like image 804
Alastair Avatar asked Sep 03 '14 22:09

Alastair


1 Answers

Change your @JsonIgnore to @JsonProperty("b"). You have correctly stated to Ignore the property 'b but 'b has not yet been annotated as a property.

@JsonIgnoreProperties(Array("b"))
case class Message(a: String, @JsonProperty("b") b: String)
like image 109
eodgooch Avatar answered Sep 22 '22 13:09

eodgooch