Java – how do I get type values from genericrecord?
I'm using Avro. I have a genericrecord I want to extract ClientID, devicename, holder In Avro schema, ClientID is integer, devicename is string, and holder is map
ClientID in Avro schema:
{ "name" : "clientId","type" : [ "null","int" ],"doc" : "hello" }
Devicename in Avro architecture:
{ "name" : "deviceName","string" ],"doc" : "test" }
Holders in Avro architecture:
{ "name" : "holder","type" : { "type" : "map","values" : "string" } }
My question is – in contrast to object, what is the recommended method for retrieving type values?
In the following code, the payload is genericrecord, from which we can get the Avro architecture That's what I'm doing now, extracting everything as a string But how can I get the input value Is there any way? I mean, whatever the data type in Avro architecture is, I just want to extract it
public static void getData(GenericRecord payload) { String id = String.valueOf(payload.get("clientId")); String name = String.valueOf(payload.get("deviceName")); // not sure how to get maps here }
So I want to extract ClientID as integer, devicename as string, holder as Java map, and map < string, string > from genericrecord? What is the best way? Can we write any utility to perform all type conversions for common records and schemas?
Solution
You should be able to convert string values to utf8, int to integer, and map to map < utf8, utf8 > This should not result in ClassCastException:
public static void getData(GenericRecord payload) { int id = (Integer) payload.get("clientId"); String name = payload.get("deviceName").toString(); // calls Utf8.toString Map<Utf8,Utf8> holder = (Map<Utf8,Utf8>) payload.get("holder"); ... }
Generally speaking, I believe you can do these actors:
>Primitives become their boxed Version (integer, double, etc.) > strings become utf8 > bytes become Java nio. ByteBuffer > array becomes Java util. Collection > map becomes Java util. Map< Utf8,[value type]>