如何设置类中的属性值并使用lift json

时间:2015-07-24 09:11:26

标签: json scala scala-2.11 lift-json

我有一个名为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":" 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

1 个答案:

答案 0 :(得分:2)

假设DateTime是Joda DateTime,您需要定义一个自定义json序列化器来序列化DateTime对象

请参阅' 序列化不支持的类型' here

序列化程序看起来像。

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