gpt4 book ai didi

json - Scala Play Json 读取

转载 作者:行者123 更新时间:2023-12-04 11:39:28 24 4
gpt4 key购买 nike

我有一个示例代码,如下所示。

import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation.ValidationError
import play.api.libs.json.Reads._

case class Retailer(firstName:String,lastName:String,email:String,mobileNo:String,password:String)
case class Business(name:String,preferredUrl:String,businessPhone:String,retailer:Retailer)

object JsonTest {
val jsonValue = """
{
"business":
{
"name":"Some Business Name",
"preferredUrl":"someurl",
"businessPhone":"somenumber",
"retailer":
{
"firstName":"Some",
"lastName":"One",
"email":"someone@somewhere.com",
"mobileNo":"someothernumber",
"password":"$^^HFKH*"
}
}

}
"""
def printJson ={

implicit val rltRds = (
(__ \ "firstName").read[String] ~
(__ \ "lastName").read[String] ~
(__ \ "email").read[String] ~
(__ \ "mobileNo").read[String] ~
(__ \ "password").read[String]
)(Retailer)

implicit val bsnsRds = (
(__ \ "name").read[String] ~
(__ \ "preferredUrl").read[String] ~
(__ \ "businessPhone").read[String] ~
(__ \ "retailer").read[Retailer](rltRds)
)(Business)


val buisness = Json.parse(jsonValue).validate[Business](bsnsRds)
val bus = new Business("Some Business","somebusinessurl","somenumber", new Retailer("Some","One","someone@somewhere.com","someothernumber","$^^HFKH*"))
//val json = Json.toJson(bus)

println(buisness)
}




def main(args: Array[String]): Unit = {
printJson
}

}

当我尝试将 json 解析为 Scala 对象(在本例中为 Business Class)时,出现 Json 验证错误。错误是
JsError(List((/retailer,List(ValidationError(validate.error.missing-path,WrappedArray()))), (/preferredUrl,List(ValidationError(validate.error.missing-path,WrappedArray()))), (/name,List(ValidationError(validate.error.missing-path,WrappedArray()))), (/businessPhone,List(ValidationError(validate.error.missing-path,WrappedArray())))))

但是,如果我的 json 就像
val jsonValue = """
{
"name":"Some Business Name",
"preferredUrl":"someurl",
"businessPhone":"somenumber",
"retailer":
{
"firstName":"Some",
"lastName":"One",
"email":"someone@somewhere.com",
"mobileNo":"someothernumber",
"password":"$^^HFKH*"
}
}
"""

请注意,外部括号“{”和“business:”键已被删除。
我得到了一个 JsSuccess。在第一种情况下,我如何编写 Json 的读取内容?
另外,我怎样才能以通用的方式做到这一点?

请帮忙。

最佳答案

只需添加 business路径中的键:

 implicit val bsnsRds = (
(__ \ "business" \ "name").read[String] ~
(__ \ "business" \ "preferredUrl").read[String] ~
(__ \ "business" \ "businessPhone").read[String] ~
(__ \ "business" \ "retailer").read[Retailer](rltRds)
)(Business)

关于json - Scala Play Json 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18122175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com