How to convert JSON to a type in Scala

后端 未结 5 1818
野性不改
野性不改 2021-02-19 04:06

My problem is I receive an JSON text from say, twitter. Then I want to convert this text to an native object in scala. Is there a standard method to do this? I\'m also using Pla

5条回答
  •  清歌不尽
    2021-02-19 04:15

    Have a look at Lift-Json. It is part of the Lift web framework, but can be used as a stand-alone library. It can parse json into case classes (and collections of those, e.g., lists and maps), and it does not require you to add annotations. It also supports rendering classes as json, and merging and querying of json.

    Here is an example taken from their website:

    import net.liftweb.json._
    implicit val formats = DefaultFormats // Brings in default date formats etc.
    
    case class Child(name: String, age: Int,
                    birthdate: Option[java.util.Date])
    case class Address(street: String, city: String)
    case class Person(name: String, address: Address,
                     children: List[Child])
    val json = parse("""
             { "name": "joe",
               "address": {
                 "street": "Bulevard",
                 "city": "Helsinki"
               },
               "children": [
                 {
                   "name": "Mary",
                   "age": 5
                   "birthdate": "2004-09-04T18:06:22Z"
                 },
                 {
                   "name": "Mazy",
                   "age": 3
                 }
               ]
             }
           """)
    
    json.extract[Person] 
    /* Person = Person(joe, Address(Bulevard,Helsinki),
                      List(Child(Mary,5,Some(Sat Sep 04 18:06:22 EEST 2004)), 
                           Child(Mazy,3,None)))
     */
    

提交回复
热议问题