Teddy Dong
Teddy Dong

Reputation: 402

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]

Upvotes: 8

Views: 12557

Answers (3)

Ira
Ira

Reputation: 764

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

Upvotes: 1

Ahmed Kamoun
Ahmed Kamoun

Reputation: 20

First of all you can't traverse a String object, so your input must be converted to JsValue to be able to traverse it:

 val json = Json.parse(string)

then the first_name attribut is of JsValue type and not a String so if you try to extract the first_name value like you do you will get always a JsResultException.

I can only explain the random appearance of JsResultException by a radom change in your first_name field json structure. make sur your sting input to traverse has always a fixed first_name filed structure.

Upvotes: -3

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

(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]

Upvotes: 7

Related Questions