json4s:使用自定义序列化程序反序列化特定字段

问题描述 投票:7回答:1

我有一个包含很多成员的案例类,其中两个是非基元的:

import com.twitter.util.Duration
case class Foo(
  a: Int,
  b: Int,
  ...,
  y: Int,
  z: Int,
  timeoutSeconds: Duration,
  runtimeMinutes: Duration)

我想将以下JSON反序列化为此case类的实例:

{
  "a": 1,
  "b": 2,
  // ...
  "y": 42,
  "z": 43,
  "timeoutSeconds": 30,
  "runtimeMinutes": 12,
}

通常,我只写json.extract[Foo]。但是,由于MappingExceptiontimeoutSeconds,我得到了一个明显的runtimeMinutes

我看过FieldSerializer,它允许在AST上进行字段转换。但是,这还不够,因为它only允许AST转换。

[我也看过扩展CustomSerializer[Duration],但是无法反省正在处理哪个JSON密钥(timeoutSecondsruntimeMinutes)。

我也可以尝试扩展CustomSerializer[Foo],但是随后我将有很多样板代码来提取ab,...,z的值。

理想情况下,我需要使用PartialFunction[JField, T]作为反序列化器的东西,这样我才可以编写:

{
  case ("timeoutSeconds", JInt(timeout) => timeout.seconds
  case ("runtimeMinutes", JInt(runtime) => runtime.minutes
}

并且依赖案例类反序列化来获取其余参数。这样的构造在json4s中可能吗?

注意,这类似于Combining type and field serializers,除了我还希望反序列化类型根据JSON密钥而有所不同。

json scala case-class json4s
1个回答
0
投票

使用Json.NET

string json = @"{

“ a”:1,“ b”:2// ...“ y”:42“ z”:43“ timeoutSeconds”:30,“ runtimeMinutes”:12}“;

BlogSites bsObj = JsonConvert.DeserializeObject<BlogSites>(json);  

Response.Write(bsObj.Name);  
© www.soinside.com 2019 - 2024. All rights reserved.