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

前端 未结 2 434
耶瑟儿~
耶瑟儿~ 2021-01-04 03:15

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

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

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 03:55

    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]))
    

    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.

    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];
    

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

    parse(json).extractOpt[someModel];
    

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

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

提交回复
热议问题