FasterXML / jackson-dataformats-binary

Uber-project for standard Jackson binary format backends: avro, cbor, ion, protobuf, smile
Apache License 2.0
310 stars 133 forks source link

Question: Embed a AvroSchema generated json string as a json attribute with Jackon ObjectMapper? #215

Closed emeraldjava closed 4 years ago

emeraldjava commented 4 years ago

Hi,

I have a scenario where i want to embed a blob of avro json as an attribute value within a json object.

{"nifiFlows":[{"action":"full","sourceAvroSchema":[{ "type": "record", "fields":[..] }],....

I have a json schema defintion for my java object which has this declaration and I'm using the 'jsonschema2pojo' maven plugin to generate my NifiFlow Pojo.

"sourceAvroSchema": {
      "type": "array",
      "items": {
        "type": "object",
        "existingJavaType": "com.fasterxml.jackson.dataformat.avro.AvroSchema",
        "description": "The source avro schema for the table or view."
      }
    },

In the example above i'm explicity telling the POJO to use 'com.fasterxml.jackson.dataformat.avro.AvroSchema'

This generates a NifiFlow class with the following @JsonProperties

import com.fasterxml.jackson.dataformat.avro.AvroSchema;

public class NifiFlow {

    @JsonProperty("sourceAvroSchema")
    public List<AvroSchema> getSourceAvroSchema() {
        return sourceAvroSchema;
    }

    @JsonProperty("sourceAvroSchema")
    public void setSourceAvroSchema(List<AvroSchema> sourceAvroSchema) {
        this.sourceAvroSchema = sourceAvroSchema;
    }

When i define my NifiFlow in code

NifiFlow nifiFlow = new NifiFlow();
binInventoryFullNifiFlow.setAction(NifiFlow.Action.FULL);

//AvroBuilder b = new AvroBuilder();
JacksonAvroBuilder b = new JacksonAvroBuilder();
binInventoryFullNifiFlow.getSourceAvroSchema().add(b.createSchema());

ObjectMapper jacksonObjectMapper = new ObjectMapper();
return jacksonObjectMapper.writeValueAsString(nifiFlow);

The JacksonAvroBuilder creates my avro schema and I then use the jackson ObjectMapper to covert the whole Java object to a json string.

I get the following Json Mapping error

com.fasterxml.jackson.databind.JsonMappingException: Not an array: {"type":"record","name":"Employee","fields":[{"name":"name","type":"string"},{"name":"age","type":"int"},{"name":"emails","type":{"type":"array","items"
:"string"}},{"name":"boss","type":["Employee","null"]}]} (through reference chain: com.emeraldjava.NifiFlow["nifiFlows"]->java.util.ArrayList[0]->com.emeraldjava.NifiFlow["sourceAvroSchema"]->java.util.ArrayList[0]->com.fasterxml.jackson.dataformat.avro.AvroSchema["avroSchema"]->org.apache.avro.Schema$RecordSchema["elementType"])
        at com.emeraldjava.nifi.ConfigTest.getNifiConfig

Can anybody advise how i instruct the ObjectMapper to handle the 'org.apache.avro.Schema$RecordSchema' type correctly?

cowtowncoder commented 4 years ago

Please use mailing list:

https://groups.google.com/forum/#!forum/jackson-user

for usage questions.