scala 使用lift-json将scala对象序列化为JSon字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2222974/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:55:41  来源:igfitidea点击:

Serializing a scala object into a JSon String using lift-json

jsonscala

提问by Ali Salehi

I am wondering, would you please let me know how can I use lift-json to serialize a simple bean class into json string (I'm using v2.0-M1). I tried:

我想知道,请让我知道如何使用lift-json 将一个简单的bean 类序列化为json 字符串(我使用的是v2.0-M1)。我试过:

val r = JsonDSL.pretty(JsonAST.render(myBean))

and I am getting

我得到

[error]  found   : MyBean
[error]  required: net.liftweb.json.JsonAST.JValue

Thanks, -A

谢谢

回答by Joni

You can "decompose" a case class into JSON and then render it. Example:

您可以将案例类“分解”为 JSON,然后呈现它。例子:

scala> import net.liftweb.json.JsonAST._
scala> import net.liftweb.json.Extraction._
scala> import net.liftweb.json.Printer._    
scala> implicit val formats = net.liftweb.json.DefaultFormats

scala> case class MyBean(name: String, age: Int)
scala> pretty(render(decompose(MyBean("joe", 35))))
res0: String = 
{
  "name":"joe",
  "age":35
}

But sometimes it is easier to use DSL syntax:

但有时使用 DSL 语法更容易:

scala> import net.liftweb.json.JsonDSL._
scala> val json = ("name" -> "joe") ~ ("age" -> 35)
scala> pretty(render(json))
res1: String = 
{
  "name":"joe",
  "age":35
}