Json4s:反序列化时在地图中保留未知字段

Json4s: keep unknown fields in a map when deserialising

我正在尝试在 Scala 中使用 json4s 解析 HTTP 端点给出的响应。返回的 Json 可能有很多字段(它们都已记录和定义,但有很多,并且可能会更改。)我不需要引用其中的许多字段,只将它们传递给其他服务来处理。

我想获取我需要的字段,并将其余字段反序列化为地图。 class 也需要正确序列化。

例如JSON 来自端点的响应:

{
 "name": "value",
 "unknown_field": "unknown",
 "unknown_array": ["one", "two", "three"],
  ...
  ... 
}

例如case class 用在代码中:

case class TestResponse(name: String, otherFields: Map[String, Any])

有没有简单的解决方法?

我已经尝试为此实现自定义序列化程序,但目前还不太顺利。看起来这将是一个足够普遍的要求。有没有办法用 json4s 做这个 OOTB?

干杯


客户序列化程序的当前尝试:

  private object TestResponseDeserializer extends CustomSerializer[TestResponse](_ => ( {
    case JObject(JField("name_one", JString(name)) :: rest) => TestType1Response(name, rest.toMap)
    case JObject(JField("name_two", JString(name)) :: rest) => TestType2Response(name, rest.toMap)
  }, {
    case testType1: TestType1Response=>
      JObject(JField("name_one", JString(testType1.name)))
    case testType2: TestType2Response=> JObject(JField("name_two", JString(testType2.name)))
  }))

我能够使用原始问题中的自定义序列化程序解决这个问题。由于不相关的问题,它对我不起作用。