Parsing a dynamic value using Lift-JSON

Let me explain this question with an example. If I have JSON as shown below:

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

[There is no limit on the number of people; a lot more people can have JSON input]

I could retrieve this JSON object for faces 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])
class of the Person class (face1: face, face2: Person)

Question: The above scenario works just fine. However, the keys must be dynamic in key / value pairs. So in the example provided by JSON, person1 and person2 can be any, I need to read them dynamically. What is the best structure for a class of people to consider this dynamic nature.

+3
source share
1 answer

One way to parse is to map the children 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, if you need to save 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)))

, , 2.8:

parse(res).extract[Map[String, Person]]
+7

Source: https://habr.com/ru/post/1746679/


All Articles