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

前端 未结 2 438
耶瑟儿~
耶瑟儿~ 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 04:15

    I've dealt with this problem when dealing with data migrations, and I wanted default values to fill undefined fields.

    My solution was to merge the defaults into the JValue before extracting the result.

      val defaultsJson = Extraction.decompose(defaults)
      val valueJson = JsonUtil.jValue(v)
      (defaultsJson merge valueJson).extract[T]
    

    JsonUtil.scala

      import org.json4s._
    
      object JsonUtil {
        import java.nio.charset.StandardCharsets.UTF_8
        import java.io.{InputStreamReader, ByteArrayInputStream}
    
        def jValue(json: String): JValue = {
          jValue(json.getBytes(UTF_8))
        }
    
        def jValue(json: Array[Byte]): JValue = {
          val reader = new InputStreamReader(new ByteArrayInputStream(json), UTF_8)
          native.JsonParser.parse(reader)
        }
      }
    

提交回复
热议问题