Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Play Json JSResultException Validation Error

I am trying to pass this json string to my other method but SOMETIMES I get this error,

play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))

I find it strange that this occurs randomly, sometimes I don't get the exception and sometimes I do. Any ideas?

Here is what my json looks like

val string = {
  "first_name" : {
    "type" : "String",
    "value" : "John"
  },
  "id" : {
    "type" : "String",
    "value" : "123456789"
  },
  "last_name" : {
    "type" : "String",
    "value" : "Smith"
  }
}

I read it like

(string \ "first_name").as[String]
like image 468
Teddy Dong Avatar asked Sep 12 '16 23:09

Teddy Dong


2 Answers

(string \ "first_name") gives JsValue not JsString so as[String] does not work.

But if you need first name value you can do

val firstName = ((json \ "first_name") \ "value").as[String]
like image 112
pamu Avatar answered Nov 16 '22 20:11

pamu


This is another option to consider for type safety while reading and writing Json with play Json API. Below I am showing using your json as example reading part and writing is analogous.

  1. Represent data as case classes.

    case Person(id:Map[String,String], firstName:Map[String,String], lastName:[String,String]

  2. Write implicit read/write for your case classes.

    implicit val PersonReads: Reads[Person]

  3. Employ plays combinator read API's. Import the implicit where u read the json and you get back the Person object. Below is the illustration.

    val personObj = Json.fromJson[Person](json)

Please have a look here https://www.playframework.com/documentation/2.6.x/ScalaJsonAutomated

like image 1
Ira Avatar answered Nov 16 '22 21:11

Ira