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

时间:2014-11-29 04:35:53

标签: json scala case-class json4s

我有一个包含许多成员的案例类,其中两个是非原始的:

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

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

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

通常情况下,我会写json.extract[Foo]。但是,由于MappingExceptiontimeoutSeconds,我得到了显而易见的runtimeMinutes

我查看了FieldSerializer,它允许对AST进行字段转换。但是,它是不够的,因为允许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键而不同。

1 个答案:

答案 0 :(得分: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);