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)
但是我很难找到适用于Scala 2.10的Json生成和反序列化的现有方法。
在Scala 2.10中有最佳实践方法吗?
答案 0 :(得分:38)
Jackson是一个快速处理JSON的Java库。杰克逊项目包裹了杰克逊,但似乎被抛弃了。我已切换到Jackson的Scala Module进行序列化和反序列化到本机Scala数据结构。
要获得此功能,请在build.sbt
中添加以下内容:
libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.1.3",
...
)
然后你的例子将逐字地使用以下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
}
}
}
其他Scala 2.10 JSON选项包括基于Programming Scala一书的Twitter scala-json - 它很简单,但却以性能为代价。还有spray-json,它使用parboiled进行解析。最后,Play's JSON handling看起来不错,但它不容易与Play项目分离。
答案 1 :(得分:7)
答案 2 :(得分:6)
我可以衷心地为scala中的json支持推荐argonaut。您需要将其配置为序列化Customer对象,只需一行:
implicit lazy val CodecCustomer: CodecJson[Customer] =
casecodec6(Customer.apply, Customer.unapply)("id","name","address","city","state","user_id")
那会让你的班级给它一个.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}")
}
}
开发人员也对人们入门也很有帮助,也很敏感。
答案 3 :(得分:4)
现在有一个Jerkson的分支在https://github.com/randhindi/jerkson支持Scala 2.10。
答案 4 :(得分:2)
因此,基于缺少错误消息和错误的示例代码,我怀疑这不仅仅是不了解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
然后,为了扭转这个过程,您需要执行以下操作:
// Person Json is a JValue here.
personJson.extract[Person]
如果那不是你遇到麻烦的部分,请告诉我,我可以尝试修改我的答案,以便更有帮助。