简体   繁体   English

我可以使json4s的提取方法不区分大小写吗?

[英]Can I make json4s's extract method case insensitive?

I am using case classes to extract json with json4s's extract method. 我正在使用案例类通过json4s的extract方法提取json。 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 . 不幸的是,我使用的“自然地球”源数据与套管不一致。在某些分辨率下,一个字段称为iso_a2 ,在某些情况下称为ISO_A2 I can only make json4s accept the one that matches the field in the case class: 我只能让json4s接受与case类中的字段匹配的那个:

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

Is there any way to make json4s ignore case and accept both? 有什么方法可以使json4s忽略大小写并接受两者吗?

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. 使用配置属性无法使其不区分大小写,但是可以通过在解析的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM