0

I am using case classes to extract json with json4s's extract method. Unfortunately, the Natural Earth source data I am using isn't consistent about casing... at some resolutions a field is called iso_a2 and at some it's ISO_A2. I can only make json4s accept the one that matches the field in the case class:

object TopoJSON {
 case class Properties(ISO_A2: String)
...
// only accepts capitalised version.

Is there any way to make json4s ignore case and accept both?

Mohan
  • 7,302
  • 5
  • 32
  • 55

1 Answers1

2

There is no way to make it case insensitive using the configuration properties, but a similar result can be achieved by either lowercasing or uppercasing the field names in the parsed JSON.

For example, we have our input:

case class Properties(iso_a2: String)
implicit val formats = DefaultFormats

val parsedLower = parse("""{ "iso_a2": "test1" }""")
val parsedUpper = parse("""{ "ISO_A2": "test2" }""")

We can lowercase all field names using a short function:

private def lowercaseAllFieldNames(json: JValue) = json transformField {
  case (field, value) => (field.toLowerCase, value)
}

or make it for specific fields only:

private def lowercaseFieldByName(fieldName: String, json: JValue) = json transformField {
  case (field, value) if field == fieldName => (fieldName.toLowerCase, value)
}

Now, to extract the case class instances:

val resultFromLower = lowercaseAllFieldNames(parsedLower).extract[Properties]
val resultFromUpper = lowercaseAllFieldNames(parsedUpper).extract[Properties]
val resultByFieldName = lowercaseFieldByName("ISO_A2", parsedUpper).extract[Properties]

// all produce expected items:
// Properties(test1)
// Properties(test2)
// Properties(test2)
Antot
  • 3,904
  • 1
  • 21
  • 27