First, if this is not the best place to put this kind of question, please let me know so I can put this somewhere else.
I have been trying to serialize this class using a custom serializer and I have been having some trouble being able to get it serialize correctly.
Here's the class I'm trying to serialize:
public class Schema {
@JsonProperty("table_constraints")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
private final Map<Constraint, Set<Column<?>>> constraints;
private final Set<Column<?>> columns;
And here is the custom serializer:
public class SchemaSerializer extends StdSerializer<Schema> {
@Override
public void serialize(
Schema schema, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
log.info("Serializing schema: " + schema.toString());
jsonGenerator.writeStartObject();
jsonGenerator.writeArrayFieldStart("columns");
for (var column : schema.getColumns()) {
jsonGenerator.writeObject(column);
}
jsonGenerator.writeEndArray();
jsonGenerator.writeArrayFieldStart("constraints");
for (var constraint : schema.getConstraints().entrySet()) {
jsonGenerator.writeStartObject();
jsonGenerator.writeObject(constraint.getKey()) <--- This line is the problem
jsonGenerator.writeArrayFieldStart("columns");
for (Column<?> column : constraint.getValue()) {
jsonGenerator.writeString(column.getName());
}
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
}
}
Here's the desired output:
columns:
- name: intColumn
type:
name: integer
- name: varcharColumn
type:
name: varchar
max_length: 1
constraints:
- type: primary_key
columns:
- intColumn
- type: unique
columns:
- varcharColumn
The constraint object is handled through annotations so I wasn't sure how to get it to just serialize the name provided in the annotation. If I try jsonGenerator.writeObjectField("type", constraint.getKey()), it wraps it with another "type" key instead of just providing the value. Any idea how to write another object within the same JsonObject?
First, if this is not the best place to put this kind of question, please let me know so I can put this somewhere else.
I have been trying to serialize this class using a custom serializer and I have been having some trouble being able to get it serialize correctly.
Here's the class I'm trying to serialize:
And here is the custom serializer:
Here's the desired output:
The constraint object is handled through annotations so I wasn't sure how to get it to just serialize the name provided in the annotation. If I try
jsonGenerator.writeObjectField("type", constraint.getKey()), it wraps it with another "type" key instead of just providing the value. Any idea how to write another object within the same JsonObject?