8

以下のようなサンプルコードがあります。

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 オブジェクト (この場合はビジネス クラス) に解析しようとすると、Json Validation Error が発生します。エラーは

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 の読み取りをどのように記述しますか? また、どうすれば一般的な方法でそれを行うことができますか?

助けてください。

4

2 に答える 2

2

上記のわずかなバリエーション:

implicit val bsnsRds = ({
  val business = (__ \ "business")
  (business \ "name").read[String] ~
  (business \ "preferredUrl").read[String] ~
  (business \ "businessPhone").read[String] ~
  (business \ "retailer").read[Retailer](rltRds)
})(Business)
于 2015-12-04T00:51:06.490 に答える