当缺少必填字段时,是否可以使 json4s 不抛出异常? [英] Is it possible to make json4s not to throw exception when required field is missing?

查看:38
本文介绍了当缺少必填字段时,是否可以使 json4s 不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让json4s在缺少必填字段时不抛出异常?

Is it possible to make json4s not to throw exception when required field is missing ?

当我从原始 json 字符串中提取"对象时,它会抛出这样的异常

When I "extract" object from raw json string it throws exception like this one

org.json4s.package$MappingException: No usable value for pager
No usable value for rpp
Did not find value which can be converted into byte
    at org.json4s.reflect.package$.fail(package.scala:98)
    at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:388)
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$11.apply(Extraction.scala:396)

是否可以让它为空?

推荐答案

很简单,你要使用 Option 和它的潜力,SomeNone.

It's quite simple, you have to use Option and its potentials, Some and None.

val json = ("name" -> "joe") ~ ("age" -> Some(35));
val json = ("name" -> "joe") ~ ("age" -> (None: Option[Int]))

请注意,在上述情况下,将为您的 Option 执行 match.如果是None,则将其从字符串中完全移除,因此不会反馈null.

Beware though, in the above case a match will be performed for your Option. If it's None, it will be completely removed from the string, so it won't feed back null.

在相同的模式中,要解析不完整的 JSON,您可以使用带有 Optioncase 类.

In the same pattern, to parse incomplete JSON, you use a case class with Option.

case class someModel(
    age: Option[Int],
    name: Option[String]
);
val json = ("name" -> "joe") ~ ("age" -> None);
parse(json).extract[someModel];

有一种方法不会抛出任何异常,那就是extractOpt

There is a method which won't throw any exception, and that is extractOpt

parse(json).extractOpt[someModel];

使用 scala API 复制它的一种方法是使用 scala.util.Try:

A way to replicate that with the scala API would be to use scala.util.Try:

Try { parse(json).extract[someModel] }.toOption

这篇关于当缺少必填字段时,是否可以使 json4s 不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆