2014-01-08 31 views
0

我給js1作爲一個字符串。 我想在「abc」下嵌套「a」,「b」,「c」。 我覺得這可以做幾行代碼。什麼是更好的方式來做到這一點?什麼是在Scala電梯JValue中改造的更好方法?

val js1 = """ 
{ 
    "name" : "test", 
    "a" : true, 
    "b" : true, 
    "c" : true, 
    "d" : true, 
    "f" : true, 
    "g" : true, 
    "h" : true, 
} 
""" 

val jsGroups = parse(js1) 

val a = (jsGroups \ "a").values.toString.toBoolean 
val b = (jsGroups \ "b").values.toString.toBoolean 
val c = (jsGroups \ "c").values.toString.toBoolean 
val abc = ("a" -> a) ~ ("b" -> b) ~ ("c" -> c) 
val r = jsGroups.remove { x => 
    x match { 
    case JField("a", bool) => true 
    case JField("b", bool) => true 
    case JField("c", bool) => true 
    case _ => false 
    } 

} 
val newJs = r.merge(JObject(List(JField("abc", abc)))) 
println(pretty(render(newJs))) 

輸出必須是

{ 「姓名」: 「測試」, 「d」:真, 「F」:真, 「G」:真, 「H」:真, 「ABC」:{ 「一」:真, 「b」:真, 「C」:真 } }

回答

1

的最簡單的方法是使用一個case class

import net.liftweb.json.{ DefaultFormats, Extraction, JsonParser } 
case class Abc(a: Boolean, b: Boolean, c: Boolean) 
implicit val formats = DefaultFormats 

// to serialize to JValue 
val test = Abc(true, true, true) 
Extraction.decompose(test) 

// to parse from String 
JsonParser.parse("""{a: true, b: true, c: true}""").extract[Abc] 
+0

我給整個js1作爲字符串tho。 –

+0

我必須刪除頂層a,b,c,幷包含d,e,f,g。它不能只是a,b,c –

相關問題