如何用部分数据从json填充案例类? [英] How to fill case class from json with partial data?

查看:32
本文介绍了如何用部分数据从json填充案例类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import net.liftweb.json._
import net.liftweb.json.JsonParser._

object test02 extends App {
    implicit val formats = DefaultFormats
    case class User(
        id: Int = 0,
        name: String = "John Doe",
        gender: String = "M")

    val s1=""" {"id":1,"name":"Bill","gender":"M"} """
    var r1=Serialization.read[User](s1)
    println(r1)

    val s2=""" {"id":1} """
    var r2=Serialization.read[User](s2)
    println(r2)  

}

第二次 Serialization.read 导致异常:net.liftweb.json.MappingException:名称无可用值.

Second Serialization.read causes exception: net.liftweb.json.MappingException: No usable value for name.

我怎么可能将数据从 json 读入 case 类,但如果某些字段丢失,它们会被 case 类中的默认值替换?

How could I possibly read data form json into case class, but if some fields are missing they are replaced with default values from case class?

推荐答案

如何使用 play json 库进行操作,但是,您必须在解析器中提供默认值,而不仅仅是作为值的默认值:

How to do it with the play json library, although, you have to provide the defaults in the parser and not only as default for the values:

case class User(id: Int, name: String, gender: String)

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit val userReads: Reads[User] = (
  (__ \ "id").read[Int] and
  (__ \ "name").read[String].or(Reads.pure("John Doe")) and
  (__ \ "gender").read[String].or(Reads.pure("Male"))
)(User)

Json.fromJson[User](Json.parse("""{"id":1,"name":"Bill","gender":"M"}"""))

Json.fromJson[User](Json.parse("""{"id":1}"""))

我想您可以通过创建 User 的模板实例,然后将默认值从每个字段传递到 Reads.pure 而不是在那里硬编码字符串来提供默认参数的默认值.

I guess you could provide the defaults from the default parameter by creating a template instance of User and then passing the default from each field to Reads.pure instead of hardcoding a string there.

这篇关于如何用部分数据从json填充案例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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