2014-01-08 43 views
0

例如我的JSON數據是這樣的:如何在提取之前將JValue變平?

[{ 
    "name": "Foo", 
    "verified": {"email": true, "mobile": false} 
}, { 
    "name": "Bar", 
    "verified": {"email": false, "mobile": false} 
}]

隨着json4s我可以得到一個JArray,提取到用戶(案例類)的列表,我要處理的JArray前 - 我要弄平verified場因此用戶會像:

case class (name: String, emailVerified: Boolean, mobileVerified: Boolean)

我怎樣才能做到這一點?

回答

2

您可以將現有的AST是這樣的:

import org.json4s._ 
import org.json4s.jackson.JsonMethods._ 
import org.json4s.JsonDSL._ 

object test extends App { 

    val json = """[{ 
      | "name": "Foo", 
      | "verified": {"email": true, "mobile": false} 
      |}, { 
      | "name": "Bar", 
      | "verified": {"email": false, "mobile": false} 
      |}]""".stripMargin 

    def t(js: JValue): JValue = for { 
    JString(name) <- js \ "name" 
    JBool(ver1) <- js \ "verified" \ "email" 
    JBool(ver2) <- js \ "verified" \ "mobile" 
    } yield ("name" -> name) ~ ("emailVerified" -> ver1) ~ ("mobileVerified" -> ver2) 

    for { 
    JArray(xs) <- parse(json) 
    } yield JArray(xs map t) 

} 

另一種選擇是爲它編寫自定義序列:

import org.json4s._ 
import org.json4s.jackson.JsonMethods._ 
import org.json4s.JsonDSL._ 

object userTest extends App { 

    val json = """{ 
       | "name": "Bar", 
       | "verified": {"email": false, "mobile": false} 
       |}""".stripMargin 

    case class UserFoo(name: String, emailVerified: Boolean, mobileVerified: Boolean) 

    class UserFooSerializer extends CustomSerializer[UserFoo](formats => ({ 
    case js: JValue => 
     val u = for { 
     JString(name) <- js \ "name" 
     JBool(userVerified) <- js \ "verified" \ "email" 
     JBool(mobileVerified) <- js \ "verified" \ "mobile" 
     } yield UserFoo(name, userVerified, mobileVerified) 
     u.head 
    }, Map.empty)) 


    implicit val formats = DefaultFormats + new UserFooSerializer 

    parse(json).extractOpt[UserFoo] map { 
    user => 
     println(user) 
     // UserFoo(Bar,false,false) 

     println(pretty(Extraction.decompose(user))) 
     // { 
     // "name" : "Bar", 
     // "emailVerified" : false, 
     // "mobileVerified" : false 
     // } 
    } 

} 
相關問題