Parsing JSON with multiple tuples to List<object> in scala

帅比萌擦擦* 提交于 2019-12-25 06:39:05

问题


[
{"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.


回答1:


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

val people = parse[List[Person]](personJson)



回答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]]


来源:https://stackoverflow.com/questions/24139359/parsing-json-with-multiple-tuples-to-listobject-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!