in lang/java/avro/src/main/java/org/apache/avro/io/parsing/ResolvingGrammarGenerator.java [254:356]
public static void encode(Encoder e, Schema s, JsonNode n) throws IOException {
switch (s.getType()) {
case RECORD:
for (Field f : s.getFields()) {
String name = f.name();
JsonNode v = n.get(name);
if (v == null) {
v = Accessor.defaultValue(f);
}
if (v == null) {
throw new AvroTypeException("No default value for: " + name);
}
encode(e, f.schema(), v);
}
break;
case ENUM:
e.writeEnum(s.getEnumOrdinal(n.textValue()));
break;
case ARRAY:
e.writeArrayStart();
e.setItemCount(n.size());
Schema i = s.getElementType();
for (JsonNode node : n) {
e.startItem();
encode(e, i, node);
}
e.writeArrayEnd();
break;
case MAP:
e.writeMapStart();
e.setItemCount(n.size());
Schema v = s.getValueType();
for (Iterator<String> it = n.fieldNames(); it.hasNext();) {
e.startItem();
String key = it.next();
e.writeString(key);
encode(e, v, n.get(key));
}
e.writeMapEnd();
break;
case UNION:
int correctIndex = 0;
List<Schema> innerTypes = s.getTypes();
while (correctIndex < innerTypes.size() && !isCompatible(innerTypes.get(correctIndex).getType(), n)) {
correctIndex++;
}
if (correctIndex >= innerTypes.size()) {
throw new AvroTypeException("Not compatible default value for union: " + n);
}
e.writeIndex(correctIndex);
encode(e, innerTypes.get(correctIndex), n);
break;
case FIXED:
if (!n.isTextual())
throw new AvroTypeException("Non-string default value for fixed: " + n);
byte[] bb = n.textValue().getBytes(StandardCharsets.ISO_8859_1);
if (bb.length != s.getFixedSize()) {
bb = Arrays.copyOf(bb, s.getFixedSize());
}
e.writeFixed(bb);
break;
case STRING:
if (!n.isTextual())
throw new AvroTypeException("Non-string default value for string: " + n);
e.writeString(n.textValue());
break;
case BYTES:
if (!n.isTextual())
throw new AvroTypeException("Non-string default value for bytes: " + n);
e.writeBytes(n.textValue().getBytes(StandardCharsets.ISO_8859_1));
break;
case INT:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for int: " + n);
e.writeInt(n.intValue());
break;
case LONG:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for long: " + n);
e.writeLong(n.longValue());
break;
case FLOAT:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for float: " + n);
e.writeFloat((float) n.doubleValue());
break;
case DOUBLE:
if (!n.isNumber())
throw new AvroTypeException("Non-numeric default value for double: " + n);
e.writeDouble(n.doubleValue());
break;
case BOOLEAN:
if (!n.isBoolean())
throw new AvroTypeException("Non-boolean default for boolean: " + n);
e.writeBoolean(n.booleanValue());
break;
case NULL:
if (!n.isNull())
throw new AvroTypeException("Non-null default value for null type: " + n);
e.writeNull();
break;
}
}