我有一些看起来像这样的json数据:
{
"id": 1998983092,
"name": "Test Name 1",
"type": "search string",
"creationDate": "2017-06-06T13:49:15.091+0000",
"lastModificationDate": "2017-06-28T14:53:19.698+0000",
"lastModifiedUsername": "testuser@test.com",
"lockedQuery": false,
"lockedByUsername": null
}
我可以毫无问题地将lockedQuery null值添加到GenericRecord对象。
GenericRecord record = new GenericData.Record(schema);
if(json.isNull("lockedQuery")){
record.put("lockedQuery", null);
}
但是,稍后当我尝试将该GenericRecord对象写入avro文件时,我得到一个空指针异常。
File file = new File("~/test.arvo");
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
dataFileWriter.create(schema, file);
for(GenericRecord record: masterList) {
dataFileWriter.append(record); // NULL POINTER HERE
}
当我运行该代码时,我得到以下异常。有关如何将空值处理成Avro文件的任何提示都非常感谢。提前谢谢。
java.lang.NullPointerException: null of boolean in field lockedQuery of
com.mydomain.test1.domain.MyAvroRecord
Exception in thread "main" java.lang.RuntimeException:
org.apache.avro.file.DataFileWriter$AppendWriteException:
java.lang.NullPointerException: null of boolean in field lockedQuery of
com.mydomain.test1.domain.MyAvroRecord
at com.mydomain.avro.App.main(App.java:198)
Caused by: org.apache.avro.file.DataFileWriter$AppendWriteException:
java.lang.NullPointerException: null of boolean in field lockedQuery of
com.mydomain.test1.domain.MyAvroRecord
at org.apache.avro.file.DataFileWriter.append(DataFileWriter.java:308)
编辑:这是MyAvroRecord
public class MyAvroRecord {
long id;
String name;
String type;
Date timestamp;
Date lastModifcationDate;
String lastModifiedUsername;
Boolean lockedQuery;
答案 0 :(得分:11)
为了能够将Avro字段设置为null
,您应该在Avro架构中允许此项,方法是添加null
作为字段的可能类型之一。请查看Avro文档中的示例:
{
"type": "record",
"name": "MyRecord",
"fields" : [
{"name": "userId", "type": "long"}, // mandatory field
{"name": "userName", "type": ["null", "string"]} // optional field
]
}
此处userName
被声明为复合类型,可以是null
或string
。这种定义允许将userName
字段设置为null。由于对比userId
只能包含长值,因此尝试将userId
设置为null将导致NullPointerException
。
答案 1 :(得分:2)
我也有这个问题,现在已经解决了。
我在Apache Avro中发现了@Nullable
批注,以声明该字段可为空。
因此,在此示例中,我们应该
import org.apache.avro.reflect.Nullable;
public class MyAvroRecord {
long id;
String name;
String type;
Date timestamp;
Date lastModifcationDate;
String lastModifiedUsername;
@Nullable
Boolean lockedQuery;
}