在JSON解析的过程中,我想捕捉一个异常,因为可选的顺序文件的模式与我的case类不同。
我有以下的case类。
case class SimpleFeature(
column: String,
valueType: String,
nullValue: String,
func: Option[String])
case class TaskConfig(
taskInfo: TaskInfo,
inputType: String,
training: Table,
testing: Table,
eval: Table,
splitStrategy: SplitStrategy,
label: Label,
simpleFeatures: Option[List[SimpleFeature]],
model: Model,
evaluation: Evaluation,
output: Output)
这是JSON文件的一部分,我想指出来。
"simpleFeatures": [
{
"column": "pcat_id",
"value": "categorical",
"nullValue": "DUMMY"
},
{
"column": "brand_code",
"valueType": "categorical",
"nullValue": "DUMMY"
}
]
正如你所看到的 第一个元素在模式中出现了错误 在解析的时候,我想提出一个错误。同时,我想保留可选行为,以防没有对象可解析。
我一直在研究的一个想法--创建自定义序列器并手动检查字段,但不确定我的方向是否正确。
object JSONSerializer extends CustomKeySerializer[SimpleFeatures](format => {
case jsonObj: JObject => {
case Some(simplFeatures (jsonObj \ "simpleFeatures")) => {
// Extraction logic goes here
}
}
})
我可能对Scala和json4s不是很精通,所以感谢任何建议。
json4s version
3.2.10
scala version
2.11.12
jdk version
1.8.0
我认为你需要扩展 CustomSerializer
阶层自 CustomKeySerializer
它是用来实现JSON键的自定义逻辑。
import org.json4s.{CustomSerializer, MappingException}
import org.json4s.JsonAST._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
case class SimpleFeature(column: String,
valueType: String,
nullValue: String,
func: Option[String])
case class TaskConfig(simpleFeatures: Option[Seq[SimpleFeature]])
object Main extends App {
implicit val formats = new DefaultFormats {
override val strictOptionParsing: Boolean = true
} + new SimpleFeatureSerializer()
class SimpleFeatureSerializer extends CustomSerializer[SimpleFeature](_ => ( {
case jsonObj: JObject =>
val requiredKeys = Set[String]("column", "valueType", "nullValue")
val diff = requiredKeys.diff(jsonObj.values.keySet)
if (diff.nonEmpty)
throw new MappingException(s"Fields [${requiredKeys.mkString(",")}] are mandatory. Missing fields: [${diff.mkString(",")}]")
val column = (jsonObj \ "column").extract[String]
val valueType = (jsonObj \ "valueType").extract[String]
val nullValue = (jsonObj \ "nullValue").extract[String]
val func = (jsonObj \ "func").extract[Option[String]]
SimpleFeature(column, valueType, nullValue, func)
}, {
case sf: SimpleFeature =>
("column" -> sf.column) ~
("valueType" -> sf.valueType) ~
("nullValue" -> sf.nullValue) ~
("func" -> sf.func)
}
))
// case 1: Test single feature
val singleFeature = """
{
"column": "pcat_id",
"valueType": "categorical",
"nullValue": "DUMMY"
}
"""
val singleFeatureValid = parse(singleFeature).extract[SimpleFeature]
println(singleFeatureValid)
// SimpleFeature(pcat_id,categorical,DUMMY,None)
// case 2: Test task config
val taskConfig = """{
"simpleFeatures": [
{
"column": "pcat_id",
"valueType": "categorical",
"nullValue": "DUMMY"
},
{
"column": "brand_code",
"valueType": "categorical",
"nullValue": "DUMMY"
}]
}"""
val taskConfigValid = parse(taskConfig).extract[TaskConfig]
println(taskConfigValid)
// TaskConfig(List(SimpleFeature(pcat_id,categorical,DUMMY,None), SimpleFeature(brand_code,categorical,DUMMY,None)))
// case 3: Invalid json
val invalidSingleFeature = """
{
"column": "pcat_id",
"value": "categorical",
"nullValue": "DUMMY"
}
"""
val singleFeatureInvalid = parse(invalidSingleFeature).extract[SimpleFeature]
// throws MappingException
}
分析❑❑:这里的主要问题是如何获得钥匙。jsonObj
为了检查是否存在无效或丢失的密钥,一种方法是通过 jsonObj.values.keySet
. 在实现上,首先我们将必选字段分配给 requiredKeys
变量,然后我们比较 requiredKeys
与目前存在的 requiredKeys.diff(jsonObj.values.keySet)
. 如果差值不为空,意味着缺少一个必填字段,在这种情况下,我们抛出一个异常,包括必要的信息。
注1.我们不应该忘记将新的序列器添加到可用的格式中。 我们不要忘了将新的序列器添加到可用的格式中.
注意2:我们不要忘记将新的序列化器添加到可用的格式中。 我们抛出一个MappingException的实例,这在json4s内部解析JSON字符串时已经使用。
更新
为了强制验证选项字段,您需要设置 strictOptionParsing
选项,通过覆盖相应的方法将其改为true。
implicit val formats = new DefaultFormats {
override val strictOptionParsing: Boolean = true
} + new SimpleFeatureSerializer()
覆盖相应的方法:
https:/nmatpt.comlog20170129json4s-custom-serializer。
你可以尝试使用 play.api.libs.json
"com.typesafe.play" %% "play-json" % "2.7.2",
"net.liftweb" % "lift-json_2.11" % "2.6.2"
你只需要定义case类和formatters。
例如,你只需要定义case class和formatters。
case class Example(a: String, b: String)
implicit val formats: DefaultFormats.type = DefaultFormats
implicit val instancesFormat= Json.format[Example]
然后只需要做.NET语句
Json.parse(jsonData).asOpt[Example]
如果上面的内容出现了一些错误。试试添加 "net.liftweb" % "lift-json_2.11" % "2.6.2"
也在你的依赖中。