如何从Avro的RECORD类型中获取类型值?

时间:2016-12-06 20:29:24

标签: java avro

我正在与Avro合作,我有GenericRecord。我想从dataTimestamp值中提取processTimestampclientIdprocessIddeviceIdgoldenHeader

  "fields" : [ {
    "name" : "goldenHeader",
    "type" : {
      "type" : "record",
      "name" : "GoldenHeader",
      "fields" : [ {
        "name" : "dataTimestamp",
        "type" : "long"
      }, {
        "name" : "processTimestamp",
        "type" : "long"
      }, {
        "name" : "clientId",
        "type" : "int"
      }, {
        "name" : "processId",
        "type" : [ "null", {
          "type" : "string",
          "avro.java.string" : "String"
        } ]
      }, {
        "name" : "deviceId",
        "type" : {
          "type" : "string",
          "avro.java.string" : "String"
        }
      } ]
    },
    "doc" : "Golden header"
  },
  .. some other fields
  ]

当我们获取数据时,我的GenericRecord看起来像这样:

{"goldenHeader": {"dataTimestamp": 1481055083500, "processTimestamp": 1481055085524, "clientId": 1234, "processId": null, "deviceId": "ducer"}}

现在我很困惑如何从goldenHeader中提取RECORD类型的单个字段。当我打印出goldenHeader的班级名称时,我看到了:

org.apache.avro.generic.GenericData.Record

以下是我的代码,但我对下一步做了什么感到困惑:

  public static Object fromAvro(Object obj, Schema schema) {
    if (obj == null) {
      return null;
    }
    System.out.println(schema.getType());
    switch (schema.getType()) {
      case RECORD:
        // not sure what to do here
    }
  }

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

如果你的对象实际上有这些字段,它的运行时类是一些子类,你只需要找出它实际上是什么类。我认为最简单的方法是instanceof

public static Object fromAvro(Object obj) {
  if (obj == null) {
    return null;
  }

  if(obj instanceof MyClass) {
    MyClass myClass = (MyClass)obj;
    GoldenHeader goldenHeader = myClass.getGoldenHeader();
    // ...
  }
}