【问题标题】:Deserializing JSON with JSON4S使用 JSON4S 反序列化 JSON
【发布时间】:2016-01-28 20:44:16
【问题描述】:

我有以下格式的 JSON:

{
  "id": 1913548255,
  "notification": "NotificationReceived",
  "deviceGuid": "e60d6085-2aba-48e9-b1c3-73c673e414be",
  "timestamp": "2016-01-28T20:34:34.167",
  "parameters": {
    "jsonString": "{\"mac\":\"bc6a29abd973\",\"uuid\":\"f000aa1104514000b000000000000000\",\"value\":0.27328648477047685}"
  }
}

我想反序列化它以获得以下类,以便:

case class Parameters(mac: String, uuid: String, value: Double)
case class Notification(id: BigInt, notification: String, deviceGuid: String, timestamp: String, perameters: Parameters)

我知道我需要写CustomSerializer。但我没有太多经验。请指导我。感谢您的帮助。

【问题讨论】:

    标签: json scala json4s


    【解决方案1】:

    我决定不处理反序列化器,而是以普通方式处理。我发布代码以便它可以帮助某人。

    case class Parameters(mac: String, uuid: String, value: Double)
    case class Notification(id: Int, notification: String, deviceGuid: String, timestamp: String, parameters: Map[String, String])
    case class FinalNotification(id: Int, notification: String, device_guid: String, timestamp: String, mac: String, uuid: String, value: Double)
    
     implicit val formats = DefaultFormats
     val n = parse(v).extract[Notification]
    
     def convertJson(json: Option[String]): Parameters = json match {
        case None => throw new IllegalArgumentException("Json can't be converted. ")
        case Some(j) => parse(j).extract[Parameters]
    }
    
    val param = convertJson(n.parameters.get("jsonString"))
    
    FinalNotification(n.id, n.notification, n.deviceGuid, n.timestamp, param.mac, param.uuid, param.value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      相关资源
      最近更新 更多