【问题标题】:Deserialise JSON to polymorphic types based on a type field基于类型字段将 JSON 反序列化为多态类型
【发布时间】:2015-09-14 22:31:06
【问题描述】:

我正在使用 lift-json 2.6 和 Scala 2.11。

我想将表示“传感器”映射的 JSON 字符串反序列化为案例类(我根本不关心序列化回 JSON):

case class TemperatureSensor(
    name: String, sensorType: String, state: TemperatureState)

case class TemperatureState(
    on: Boolean, temperature: Float)

case class LightSensor(
    name: String, sensorType: String, state: LightState)

case class LightState(
    on: Boolean, daylight: Boolean)

我这里有每个传感器类中的一些公共字段,具有类型相关的 state 字段,由 sensorType 属性区分

我的想法是调用 Web 服务并获取传感器信息的地图,这可以是任意数量的任何类型的不同传感器。我事先知道可能的类型集合,但我事先不知道将返回哪些特定传感器。

JSON 看起来像这样:

{
  "1":
    {
      name: "Temp1",
      sensorType: "Temperature",
      state:
        {
          on: true,
          temperature: 19.4
        }
    },
  "2":
    {
      name: "Day",
      sensorType: "Daylight",
      state:
        {
           on: true,
           daylight: false
        }
    }
}

(真实数据有更多字段,以上案例类和JSON是缩减版。)

要使用我开始的 JSON:

val map = parse(jsonString).extract[Map[String,Sensor]]

当然,当我省略 state 字段时,这有效。

如何根据sensorType 字段的值,告诉提取过程在运行时选择哪种类型的state?还是我必须编写自定义反序列化器?

这个问题专门与 lift-json 相关,而不是任何其他 JSON 库。

【问题讨论】:

标签: scala lift-json


【解决方案1】:

不幸的是,我没有使用lift-json...但是我最近使用play-json 解决了同样的问题。也许我所做的一些事情也对你有用。

代码见我的github页面:DiscriminatedCombinators.scala

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    相关资源
    最近更新 更多