Search code examples
jsonscalajacksonjson4s

Json4s (Native/Jackson) Ignore all unknown fields


When using Json4s it was very clear you can explicitly ignore specific fields. However, I don't see any documentation on how to ignore all unknown fields.

In Jackson, I would use the following annotation:

import com.fasterxml.jackson.annotation._

@JsonIgnoreProperties(ignoreUnknown=true)
case class MyClass(string: String)

How do I do this with either the Jackson or Native version of Json4s?


Solution

  • I'm not quite sure, if I get you here, but Json4s (at least the org.json4s version) ignores additional fields by default.

    import org.json4s.DefaultFormats
    import org.json4s.native.JsonMethods._
    
    implicit val formats = DefaultFormats
    case class Mailserver(url: String, username: String, password: String)
    
    val json = parse(
    """
      {
        "url": "imap.yahoo.com",
        "username": "myusername",
        "password": "mypassword",
        "additional": "field"
      }
    """
    )
    
    val m = json.extract[Mailserver]
    println(m.url)
    println(m.username)
    println(m.password)
    

    This works fine.