scala 如何在 Lift 中将 JSON JString 值转换为普通字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7781877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a JSON JString value to an ordinary String in Lift?
提问by Ivan
Having a jString : JStringvalue holding an "abc"string inside I get "JString(abc)" : Stringif I call jString.toString. How do I get "abc" : Stringinstead?
有一个jString : JString拿着值"abc"的字符串中,我得到"JString(abc)" : String,如果我打电话jString.toString。我如何获得"abc" : String?
回答by Joni
To extract a value from JValue you can use any method described here: What is the most straightforward way to parse JSON in Scala?
要从 JValue 中提取值,您可以使用此处描述的任何方法:在 Scala 中解析 JSON 的最直接方法是什么?
For instance:
例如:
json.extract[String]
You can use 'render' function to convert any JValue to printable format. Then either 'pretty' or 'compact' will convert that to a String.
您可以使用“渲染”函数将任何 JValue 转换为可打印格式。然后“漂亮”或“紧凑”将其转换为字符串。
compact(render(json))
or
或者
pretty(render(json))
回答by Win Myo Htet
val jstring=JString("abc")
implicit val formats = net.liftweb.json.DefaultFormats
System.out.println(jstring.extract[String])
回答by Vlad Patryshev
I believe the best way is to use match:
我相信最好的方法是使用 match:
val x = ... (whatever, maybe it's a JString)
x match {
case JString(s) => do something with s
case _ => oops, something went wrong
}
回答by Necro
This was asked a while ago, but I wanted a simple one-line helper that would get my string for me in the context of an expression, so I wrote this little thing inside of an object called Get:
不久前有人问过这个问题,但我想要一个简单的单行助手,它可以在表达式的上下文中为我获取我的字符串,所以我在一个名为 Get 的对象中编写了这个小东西:
object Get {
def string(value: JValue): String = {
val JString(result) = value
result
}
...
}
This way I can just do, e.g., val myString = Get.string(jsonStringValue)
这样我就可以做,例如, val myString = Get.string(jsonStringValue)

