我有一个名为Child
的类,我想使用Lift JSON转换为JSON。一切都很好,但问题是我正在通过Scala setter设置属性的值,但这个新值没有存储在Json中。
代码如下:
case class Child1(var str:String, var Num:Int, MyList:List[Int], myDate:DateTime){
var number:Int=555
}
val c = Child1("Mary", 5, List(1, 2), DateTime.now())
c.number = 1
println("number" + c.number)
val ser = write(c)
println("Child class converted to string" + ser)
var obj = read[Child1](ser)
println("object of Child is "+ obj)
println("str" + obj.str)
println("Num" + obj.Num)
println("MyList" + obj.MyList)
println("myDate" + obj.myDate)
println("number" + obj.number)
在控制台上打印的输出是:
number1
子类转换为字符串{"str":"玛丽","Num":5"MyList":[1、2],"替换":{}}
object of Child is Child1(Mary,5,List(1,2),2015-07-24T14:04:09.266+05:00)
strMary
Num5
MyListList(1、2)
myDate2015-07-24T14:04:09.266 +凌晨
555号
为什么obj.number
显示的值是555
?它应该打印1
假设DateTime是Joda DateTime,您需要定义一个自定义json序列化器来序列化DateTime对象
请参阅'序列化不支持的类型'一节在这里
序列化器看起来像。
import org.joda.time.DateTime
import net.liftweb.json.Serialization.{ read, write }
import net.liftweb.json.DefaultFormats
import net.liftweb.json.Serializer
import net.liftweb.json.JsonAST._
import net.liftweb.json.Formats
import net.liftweb.json.TypeInfo
import net.liftweb.json.MappingException
import net.liftweb.json.FieldSerializer
class JodaDateTimeSerializer extends Serializer[DateTime] {
private val JodaDateTimeClass = classOf[DateTime]
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), DateTime] = {
case (TypeInfo(JodaDateTimeClass, _), json) => json match {
case JInt(timemillis) => new DateTime(timemillis.longValue)
case x => throw new MappingException("Can't convert " + x + " to DateTime")
}
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case x: DateTime => JInt(BigInt(x.getMillis))
}
}
也定义你的格式,像这样
implicit val formats = DefaultFormats + new JodaDateTimeSerializer + new FieldSerializer[Child1]
请注意FieldSerializer序列化非构造函数字段的用法,number