2016-12-06 41 views
0

我正在和Avro合作,我有一个GenericRecord。我想提取dataTimestamp,processTimestamp,clientId,processIddeviceIdgoldenHeader的值。如何从Avro的RECORD类型获取输入值?

"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

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

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

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

那么我没有任何pojo的东西在这里。所以我需要以某种方式手动提取它。 – john

+0

你的意思是当你做'obj.getClass()'它返回'java.lang.Object'吗?然后我不确定你是否真的将数据传递给Java。 – Adam