1

I have a Json object stored in Mongo like below. It is 'flat', i.e. no nested elements:

{
   "key1" : "val1",
   "key2" : "val2",
    ....
   "keyn" : "valn"

}

I have fetched it as a JsArray. I also have a case class:

case class IndividualProduct(key1: String, key2: String, ... , key_n: String) {}

In total the Json will have over 40 key/value pairs. Is there a neat way to parse the JsArray into the case class without verbosely referencing the keys?

thanks in advance - Future[Thanks]

5
  • Wait, as JsArray? Since that's not an array, it should fail. Just fetch it as JsObject instead. Commented Feb 25, 2014 at 13:17
  • my apologies for not being clearer. The Json is as represented above, but I have managed to get it as a JsArray from using the ReactiveMongo plugin. Commented Feb 25, 2014 at 13:21
  • Then change to JsObject, what's the problem? Maybe you should post that part too, because currently it doesn't make sense. Commented Feb 25, 2014 at 13:37
  • Ok, so if I have a JsObject then what do I do to read the values out of it? Commented Feb 25, 2014 at 14:25
  • Then you refer to my answer Commented Feb 25, 2014 at 14:26

2 Answers 2

1
import play.api.libs.json._
implicit val reader = Json.reads[IndividualProduct]
val ip = Json.fromJson[IndividualProduct](fetchedJsObj)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, is the fetchedJsObj the JsArray I have? And does this reader then create the case class with all the fields?
That's the JsObject that you should have. Json.reads is a macro that creates a reader from your case class. For more info refer to the official docs, they explain all that stuff.
0

That's not a JsArray, but rather a Map[String, String]. So if you have a json like the one you showed, here's what can work:

val json = getYourJsonFromDB()
val kv = json.as[Map[String, String]]

Now you'll be able to do something like this:

val valueForKey13 = kv.get("key13") //returns an Option[String]

Hope this helps

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.