Json4s超类

时间:2015-11-18 11:55:27

标签: java json scala json4s

我无法为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

我希望能够使用以下内容阅读BasicExpressionBooleanExpression的JSON,例如:

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,但是不必为每个{{1}膨胀JSON都是好的}。我也可以尝试Condition,如果失败,请尝试extract[BooleanExpression],但这看起来很难看。是否可以编写自定义序列化程序来处理extract[BasicExpression]本身包含另一个BooleanCondition递归的事实,以便我可以Condition

2 个答案:

答案 0 :(得分:0)

为了更好地解析JSON,你可以试试这个:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class GsonUtils {

public static String defaultDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ssZ";
private static GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(defaultDateTimeFormat);

/***
 * Creates a GSON instance from the builder with the default date/time format
 *
 * @return the GSON instance
 */
public static Gson createGson() {
    // Create with default params
    gsonBuilder = gsonBuilder.setDateFormat(defaultDateTimeFormat);
    return gsonBuilder.create();
}

/***
 * Creates a GSON instance from the builder specifying custom date/time format
 *
 * @return the GSON instance
 */
public static Gson createGson(String dateTimeFormat) {
    // Create with the specified dateTimeFormat
    gsonBuilder = gsonBuilder.setDateFormat(dateTimeFormat);
    return gsonBuilder.create();
}

}

并像这样使用

  var String = """ {"field":"name","operator":"=","value":"adam"}""";

  Type collectionType = new TypeToken<YOUR_CLASS>() {}.getType();
  YOUR_CLASS iii=  GsonUtils.createGson().fromJson(jsonStringBasic, collectionType);

答案 1 :(得分:0)

管理以使CustomSerializer工作,以便在BooleanExpression的情况下递归调用自身,如下所示:

NullReferenceException