*/
public Writable serialize(Object obj, ObjectInspector objInspector)
throws SerDeException {
if (objInspector.getCategory() != Category.STRUCT) {
throw new SerDeException(getClass().toString()
+ " can only serialize struct types, but we got: "
+ objInspector.getTypeName());
}
// Prepare the field ObjectInspectors
StructObjectInspector soi = (StructObjectInspector)objInspector;
List<? extends StructField> fields = soi.getAllStructFieldRefs();
List<Object> list = soi.getStructFieldsDataAsList(obj);
List<? extends StructField> declaredFields =(serdeParams.rowTypeInfo != null && ((StructTypeInfo) serdeParams.rowTypeInfo)
.getAllStructFieldNames().size()>0)? ((StructObjectInspector)getObjectInspector())
.getAllStructFieldRefs()
: null;
serializeStream.reset();
try {
// Serialize each field
for (int i=0; i<fields.size(); i++) {
// Append the separator if needed.
if (i>0) {
serializeStream.write(serdeParams.separators[0]);
}
// Get the field objectInspector and the field object.
ObjectInspector foi = fields.get(i).getFieldObjectInspector();
Object f = (list == null ? null : list.get(i));
if (declaredFields != null && i >= declaredFields.size()) {
throw new SerDeException(
"Error: expecting " + declaredFields.size()
+ " but asking for field " + i + "\n" + "data=" + obj + "\n"
+ "tableType=" + serdeParams.rowTypeInfo.toString() + "\n"
+ "dataType="
+ TypeInfoUtils.getTypeInfoFromObjectInspector(objInspector));
}
// If the field that is passed in is NOT a primitive, and either the
// field is not declared (no schema was given at initialization), or
// the field is declared as a primitive in initialization, serialize
// the data to JSON string. Otherwise serialize the data in the
// delimited way.
if (!foi.getCategory().equals(Category.PRIMITIVE)
&& (declaredFields == null ||
declaredFields.get(i).getFieldObjectInspector().getCategory()
.equals(Category.PRIMITIVE) || useJSONSerialize)) {
serialize(serializeStream, SerDeUtils.getJSONString(f, foi),
PrimitiveObjectInspectorFactory.javaStringObjectInspector,
serdeParams.separators, 1, serdeParams.nullSequence,
serdeParams.escaped, serdeParams.escapeChar,
serdeParams.needsEscape);
} else {
serialize(serializeStream, f, foi, serdeParams.separators, 1,
serdeParams.nullSequence, serdeParams.escaped, serdeParams.escapeChar,
serdeParams.needsEscape);
}
}
} catch (IOException e) {
throw new SerDeException(e);
}
// TODO: The copy of data is unnecessary, but there is no work-around
// since we cannot directly set the private byte[] field inside Text.
serializeCache.set(serializeStream.getData(), 0,
serializeStream.getCount());