0
[
{"fname":"Foo","lname":"Pacman"},
{"fname":"Bar","lname":"Mario"},
{"fname":"Poo","lname":"Wario"}
]

Well I have JSON string in this format, Now what I need is to convert each tuples -> {"fname":"Foo","lname":"Pacman"}

To a Person object, for e.g. lets assume I have a case class

case class Person(fname:String,lname:String)

Now how am I to get, List<person>

If I had a JSON containing data for single tuple, then I could,

val o:Person = parse[Person](jsonString)// I am actually using Jerkson Lib

But since there are more than one tuples, how am i to parse them individually and create objects and create a list.

5
  • 1
    Have you tried parse[List[Person]]? Doesn't that work? Commented Jun 10, 2014 at 11:15
  • Ya tried that just now and it works.... Funny , was a 1 line answer val parsedList = parse[List[Person]](jsonString) Commented Jun 10, 2014 at 11:22
  • given the minor syntax error at hand, consider deleting the question. Commented Jun 10, 2014 at 11:29
  • 1
    Ok, I will but dont you think some one might find it handy?? Like, how much time I looked around the web for this answer. Commented Jun 10, 2014 at 11:32
  • 1
    Then it should have a proper answer. @cmbaxter, would you put your solution as an answer? Commented Jun 10, 2014 at 11:53

2 Answers 2

2

Jerkson supports deserializing lists of objects out of the box, so all you should need to do is:

val people = parse[List[Person]](personJson)
Sign up to request clarification or add additional context in comments.

Comments

2

You can use json4s (which is a wrapper around either jackson or lift-json) where you also get such parsing capabilities out of the box.

   import org.json4s._
   import org.json4s.jackson.JsonMethods._
   implicit val formats = DefaultFormats 

    val personJson = """
      [
      {"fname":"Foo","lname":"Pacman"},
      {"fname":"Bar","lname":"Mario"},
      {"fname":"Poo","lname":"Wario"}
      ]"""
    case class Person(fname:String,lname:String)
    val people = parse(personJson).extract[List[Person]]

2 Comments

umm, will give json4s a try too for my next projects, since Jerkson doesn't seem to be actively developed, thanks for the answer
I am using it myself now, seems to be fine. success with your projects :)

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.