我正在与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
    }
  }


做这个的最好方式是什么?

最佳答案

如果您的对象上确实有那些字段,则它的运行时类是某个子类,您只需找出它实际是什么类即可。我认为最简单的方法是instanceof

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

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

关于java - 如何从Avro中的RECORD类型获取键入的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41004277/

10-10 01:44