我正在与Avro合作,我有GenericRecord
。我想从dataTimestamp
值中提取processTimestamp
,clientId
,processId
,deviceId
和goldenHeader
。
"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
}
}
这样做的最佳方式是什么?
答案 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();
// ...
}
}