Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse and extract information from json array using json4s

Tags:

json

scala

json4s

I am currently trying to extract the information from a json array using json4s (scala).

An example data is as follows:

val json = """
  [
    {"name": "Foo", "emails": ["[email protected]", "[email protected]"]},
    {"name": "Bar", "emails": ["[email protected]", "[email protected]"]}
  ]
"""

And my code is as follows:

case class User(name: String, emails: List[String])
case class UserList(users: List[User]) {
  override def toString(): String = {
    this.users.foldLeft("")((a, b) => a + b.toString)
  }
}

val obj = parse(json).extract[UserList]
printf("type: %s\n", obj.getClass)
printf("users: %s\n", obj.users.toString)

The output turns out to be:

type: class UserList
users: List()

It seems that the data is not correctly retrieved. Is there any problem with my code?

UPDATE: It works according to the suggestion of @Kulu Limpa.

like image 262
yxjiang Avatar asked Nov 21 '14 01:11

yxjiang


1 Answers

Your code is correct except that your JSON is simply an array, hence a List[User]. There are two ways to fix this, with a slightly different outcome:

Solution 1: Fix your json to

{"users": 
  [
    {"name": "Foo", "emails": ["[email protected]", "[email protected]"]},
    {"name": "Bar", "emails": ["[email protected]", "[email protected]"]}
  ]
}

Solution2: Change the type parameter of extract to

val obj = parse(json).extract[List[User]]
like image 109
Kulu Limpa Avatar answered Oct 12 '22 05:10

Kulu Limpa