8

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]
2
  • 1
    What result do you get when you don't get an exception? Because the value of first_name field apparently is not just a string value. Commented Sep 13, 2016 at 0:07
  • 1
    And string is not Json. Commented Sep 13, 2016 at 4:47

3 Answers 3

7

(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]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

-3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.