0

我得到了 js1 作为字符串。我想在“ ”下嵌套“ a”、“ b”、“ ”。我感觉这几行代码就可以搞定。下面有什么更好的方法来做到这一点?cabc

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”:{“a”:真,“b”:真, “c”:真 } }

4

1 回答 1

1

The simplest way is to use a 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]
于 2014-01-08T23:58:19.070 回答