Java – NullPointerException in Avro reflectdatumwriter
•
Java
I have a specific problem with Avro serialization of Java objects I have POJOs generated from the XSD schema, and then I try to use Avro serialization to place them on the Kafka topic Some xmlelements are optional
The test message is as follows:
@XmlRootElement(name = "message")
public class Testmessage {
@XmlElement
public String id;
@XmlElement
public String name;
public Testmessage(String id,String name) {
this.id = id;
this.name = name;
}
public Testmessage() { }
@Override
public String toString() {
return "Message{" +
"id='" + id + '\'' +
",name=" + name +
'}';
}
}
The methods for serializing and placing topics are:
public void sendMessage(Testmessage msg) throws Exception{
DatumWriter<Testmessage> writer = new ReflectDatumWriter<Testmessage>(Testmessage.class);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Encoder encoder = EncoderFactory.get().binaryEncoder(os,null);
writer.write(msg,encoder);
encoder.flush();
os.close();
KeyedMessage<String,byte[]> data = new KeyedMessage<String,byte[]>(TOPIC_NAME,os.toByteArray());
producer.send(data);
}
When I send two fields, all work as expected If I leave one of the fields empty or missing, I get NPE from the write
java.lang.NullPointerException: in Testmessage in string null of string in field id of Testmessage at org.apache.avro.reflect.ReflectDatumWriter.write(ReflectDatumWriter.java:145) at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:58)
Any ideas? Or point me in the right direction
thank you!
Solution
It seems that I decided to solve this problem myself after publishing, and then read the Internet a few days later
ReflectData reflectData = ReflectData.AllowNull.get();
Schema schema = reflectData.getSchema(Testmessage.class);
DatumWriter<Testmessage> writer = new ReflectDatumWriter<Testmessage>(schema);
It seems nice to allow null
To my next mistake! yes
org.apache.avro.UnresolvedUnionException: Not in union ["null",{"type":"record","name":"XMLGregorianCalendar","namespace":"javax.xml.datatype","fields":[]}]: 2014-10-22
at org.apache.avro.generic.GenericData.resolveUnion(GenericData.java:604)
at org.apache.avro.generic.GenericDatumWriter.resolveUnion(GenericDatumWriter.java:151)
at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:71)
at org.apache.avro.reflect.ReflectDatumWriter.write(ReflectDatumWriter.java:143)
at org.apache.avro.generic.GenericDatumWriter.writeField(GenericDatumWriter.java:114)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
