2

我有一个名为的类Child,我想使用 Lift Json 将其转换为 JSON。一切正常,但问题是我正在通过 Scala 设置器设置属性的值,但这个新值没有存储在 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":"Mary","Num":5,"MyList":[1,2],"myDate":{}}
Child 的对象是 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+05:00
编号 555

为什么obj.number显示价值555?它应该打印1

4

1 回答 1

2

假设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序列化非构造函数字段,编号

于 2015-07-24T10:44:12.940 回答