我無法爲Json4s編寫自定義序列化程序來處理以下情況。我有case類:Json4s超類的序列化
trait Condition
case class BasicExpression (field:String, operator:String, value:String) extends Condition
case class BooleanExpression (val leftExpr: Condition, val logicalOperator:String,
val rightExpr: Condition) extends Condition
,我希望能夠讀取JSON兩個BasicExpression
和BooleanExpression
使用,例如:
var jsonStringBasic:String = """ {"field":"name","operator":"=","value":"adam"}""";
var jsonStringBoolean:String = """{"leftExpr":{"leftExpr":{"field":"field1", "operator":"=", "value":"value1"}, "logicalOperator":"AND", "rightExpr":{"field":"field2","operator":">","value":"500"}}, "logicalOperator":"AND", "rightExpr": {"field":"field3","operator":"<","value":"10000"}}""";
var jValueBasic:JValue = parse(jsonStringBasic, false);
var readCBasic = jValueBasic.extract[Condition];
我明白了定製串行器是如何工作的讀取BasicExpression
,並且我可以使用SimpleTypeHints
,但不必爲每個Condition
都膨脹JSON。我也可以嘗試extract[BooleanExpression]
,如果失敗嘗試extract[BasicExpression]
,但看起來很難看。是否可以編寫自定義序列化程序來處理這個事實:BooleanCondition
本身將包含另一個Condition
,因此我可以extract[Condition]
?
感謝您的建議 - 我轉向Gson了一下,但當Gson不支持Scala列表或地圖時遇到了更多問題,於是我回到Json4s,想出瞭如何編寫serialiser – adambriffett