use*_*607 36 json scala scala-2.10 lift-json
Scala 2.10似乎打破了一些旧的库(至少目前为止),比如Jerkson和lift-json.
目标可用性如下:
case class Person(name: String, height: String, attributes: Map[String, String], friends: List[String])
//to serialize
val person = Person("Name", ....)
val json = serialize(person)
//to deserialize
val sameperson = deserialize[Person](json)
Run Code Online (Sandbox Code Playgroud)
但是我很难找到适用于Scala 2.10的Json生成和反序列化的现有方法.
在Scala 2.10中有最佳实践方法吗?
Kip*_*ros 38
Jackson是一个快速处理JSON的Java库.杰克逊项目包裹了杰克逊,但似乎被抛弃了.我已经切换到Jackson的Scala模块进行序列化和反序列化到本机Scala数据结构.
要获得它,请在以下内容中包含以下内容build.sbt:
libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.1.3",
...
)
Run Code Online (Sandbox Code Playgroud)
然后你的例子将逐字地使用以下Jackson包装器(我从jackson-module-scala测试文件中提取它):
import java.lang.reflect.{Type, ParameterizedType}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.`type`.TypeReference;
object JacksonWrapper {
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
def serialize(value: Any): String = {
import java.io.StringWriter
val writer = new StringWriter()
mapper.writeValue(writer, value)
writer.toString
}
def deserialize[T: Manifest](value: String) : T =
mapper.readValue(value, typeReference[T])
private [this] def typeReference[T: Manifest] = new TypeReference[T] {
override def getType = typeFromManifest(manifest[T])
}
private [this] def typeFromManifest(m: Manifest[_]): Type = {
if (m.typeArguments.isEmpty) { m.erasure }
else new ParameterizedType {
def getRawType = m.erasure
def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
}
Run Code Online (Sandbox Code Playgroud)
其他Scala 2.10 JSON选项包括基于Programming Scala一书的Twitter的scala-json - 它很简单,但代价是性能.还有spray-json,它使用parboiled进行解析.最后,Play的JSON处理看起来不错,但它不容易与Play项目分离.
我可以衷心地推荐argonaut用于scala中的json支持.您需要将其配置为序列化Customer对象,只需一行:
implicit lazy val CodecCustomer: CodecJson[Customer] =
casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id")
Run Code Online (Sandbox Code Playgroud)
那将皮条客你的类给它一个.asJson方法,把它变成一个字符串.它还将对字符串类进行操作,以便为其提供.decodeOption[List[Customer]]解析字符串的方法.它可以很好地处理你班上的选项.这是一个带有传递测试和运行main方法的工作类,你可以将它放入argonaut的git clone中,看看它一切正常:
package argonaut.example
import org.specs2.{ScalaCheck, Specification}
import argonaut.CodecJson
import argonaut.Argonaut._
case class Customer(id: Int, name: String, address: Option[String],
city: Option[String], state: Option[String], user_id: Int)
class CustomerExample extends Specification with ScalaCheck {
import CustomerExample.CodecCustomer
import CustomerExample.customers
def is = "Stackoverflow question 12591457 example" ^
"round trip customers to and from json strings " ! {
customers.asJson.as[List[Customer]].toOption must beSome(customers)
}
}
object CustomerExample {
implicit lazy val CodecCustomer: CodecJson[Customer] =
casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id")
val customers = List(
Customer(1,"one",Some("one street"),Some("one city"),Some("one state"),1)
, Customer(2,"two",None,Some("two city"),Some("two state"),2)
, Customer(3,"three",Some("three address"),None,Some("three state"),3)
, Customer(4,"four",Some("four address"),Some("four city"),None,4)
)
def main(args: Array[String]): Unit = {
println(s"Customers converted into json string:\n ${customers.asJson}")
val jsonString =
"""[
| {"city":"one city","name":"one","state":"one state","user_id":1,"id":1,"address":"one street"}
| ,{"city":"two city","name":"two","state":"two state","user_id":2,"id":2}
| ,{"name":"three","state":"three state","user_id":3,"id":3,"address":"three address"}
| ,{"city":"four city","name":"four","user_id":4,"id":4,"address":"four address"}
|]""".stripMargin
var parsed: Option[List[Customer]] = jsonString.decodeOption[List[Customer]]
println(s"Json string turned back into customers:\n ${parsed.get}")
}
}
Run Code Online (Sandbox Code Playgroud)
开发人员也对人们的入门帮助和响应.
因此,基于没有错误消息和不正确的示例代码,我怀疑这更多是一个不了解 lift-json 提取如何工作的问题。如果我误解了,请发表评论并让我知道。所以,如果我是对的,那么这就是你所需要的。
序列化:
import net.liftweb.json._
import Extraction._
implicit val formats = DefaultFormats
case class Person(...)
val person = Person(...)
val personJson = decompose(person) // Results in a JValue
Run Code Online (Sandbox Code Playgroud)
然后要反转该过程,您可以执行以下操作:
// Person Json is a JValue here.
personJson.extract[Person]
Run Code Online (Sandbox Code Playgroud)
如果这不是您遇到问题的部分,请告诉我,我可以尝试修改我的答案以提供更多帮助。