tags:

views:

116

answers:

1

Let me explain this question with an example. If I have a JSON like the following:

{"person1":{"name": "Name One", "address": {"street": "Some Street","city": "Some City"}},
"person2":{"name": "Name Two", "address": {"street": "Some Other Street","city": "Some Other City"}}}

[There is no restriction on the number of persons, the input JSON can have many more persons]

I could extract this JSON to Persons object by doing

var persons = parse(res).extract[T]

Here are the related case classes:

case class Address(street: String, city: String)
case class Person(name: String, address: Address, children: List[Child])
case class Persons(person1: Person, person2: Person)

Question: The above scenario works perfectly fine. However the need is that the keys are dynamic in the key/value pairs. So in the example JSON provided, person1 and person2 could be anything, I need to read them dynamically. What's the best possible structure for Persons class to account for that dynamic nature.

+3  A: 

Hi,

One way to parse that is to map over child elements of the root JSON object:

scala> parse(res).children.map(_.extract[Person])
res3: List[Person] = List(Person(Name One,Address(Some Street,Some City)), Person(Name Two,Address(Some Other Street,Some Other City)))

Or like this if you need to preserve the field names:

scala> Map() ++ parse(res).children.map { case f: JField => (f.name, f.extract[Person]) }
res4: scala.collection.immutable.Map[String,Person] = Map(person1 -> Person(Name One,Address(Some Street,Some City)), person2 -> Person(Name Two,Address(Some Other Street,Some Other City)))

Note, the following direct way should work when we start to use 2.8 features:

parse(res).extract[Map[String, Person]]
Joni
@Joni Great! that worked like charm. BTW you did a great job with lift-json, simply superb. I would love to use Maps and Lists at the root-level, hopefully some time soon.
Surya Suravarapu
Thanks Surya! I'm eagerly waiting for full transition to 2.8 too. I guess we will begin to use 2.8 features after Lift 2.0 is released (the first release candidate is out soon).
Joni