Java 在Circe中处理具有不同数据类型的json
在我的例子中,同一个json字段可能有不同的数据类型。例如:Java 在Circe中处理具有不同数据类型的json,java,json,scala,circe,Java,Json,Scala,Circe,在我的例子中,同一个json字段可能有不同的数据类型。例如: "need_exp":1500 或 如何处理这个案件?我知道它可以通过parse或使用自定义编码器进行处理,但这是一个非常复杂的json文本,有没有办法在不重写整个解码器的情况下解决这个问题(例如,只需“告诉”解码器将need\u exp字段中的所有Int转换为String 它被称为析取,可以使用Scala标准或类对其进行编码。 只需将json映射到以下类: case class Foo(need_exp: Either[Strin
"need_exp":1500
或
如何处理这个案件?我知道它可以通过
parse
或使用自定义编码器进行处理,但这是一个非常复杂的json文本,有没有办法在不重写整个解码器的情况下解决这个问题(例如,只需“告诉”解码器将need\u exp
字段中的所有Int
转换为String
它被称为析取,可以使用Scala标准或类对其进行编码。
只需将json映射到以下类:
case class Foo(need_exp: Either[String, Int])
我的解决方案是使用自定义解码器。重写JSON的一小部分就可以了
例如,有一个简单的JSON:
{
/*many fields*/
"hotList":[/* ... many lists inside*/],
"list":[ {/*... many fields*/
"level_info":{
"current_exp":11463,
"current_level":5,
"current_min":10800,
"next_exp":28800 //there is the problem
},
"sex":"\u4fdd\u5bc6"},/*...many lists*/]
}
在这种情况下,我不需要重写整个JSON编码器,只需编写一个level\u info
的自定义编码器:
implicit val decodeUserLevel: Decoder[UserLevel] = (c: HCursor) => for
{
current_exp <- c.downField("current_exp").as[Int]
current_level <- c.downField("current_level").as[Int]
current_min <- c.downField("current_min").as[Int]
next_exp <- c.downField("next_exp").withFocus(_.mapString
{
case """-""" => "-1"
case default => default
}).as[Int]
} yield
{
UserLevel(current_exp, current_level, current_min, next_exp)
}
implicit val decodeUserLevel:Decoder[UserLevel]=(c:HCursor)=>for
{
使用自定义解码器检查Json
类型的当前\u exp如果该字段是选项[Int]
?
implicit val decodeUserLevel: Decoder[UserLevel] = (c: HCursor) => for
{
current_exp <- c.downField("current_exp").as[Int]
current_level <- c.downField("current_level").as[Int]
current_min <- c.downField("current_min").as[Int]
next_exp <- c.downField("next_exp").withFocus(_.mapString
{
case """-""" => "-1"
case default => default
}).as[Int]
} yield
{
UserLevel(current_exp, current_level, current_min, next_exp)
}