Skip to content

[avro] java.io.IOException: Invalid Union index (-40); union only has 2 types #123

@vicenteg

Description

@vicenteg

Unsure if I'm doing something wrong here. I want to deserialize Avro to a Json string.

I've boiled my issue down to the following:

  public static void main(String[] args) {
    String inputFile = "test.avro";
    MappingIterator<JsonNode> it = null;

    try {
      Schema jsonSchema =
          new Schema.Parser().setValidate(true).parse(new File(inputFile + ".schema"));
      AvroSchema schema = new AvroSchema(jsonSchema);

      AvroMapper avroMapper = new AvroMapper();
      avroMapper.schemaFrom(new File(inputFile + ".schema"));
      it = avroMapper.readerFor(JsonNode.class).with(schema).readValues(new FileInputStream(inputFile));
    } catch (IOException ex) {
      System.err.println("Could not open " + inputFile + " : " + ex.getMessage());
      System.exit(1);
    }

    while (it.hasNext()) {
      JsonNode row = it.next();
      System.out.println(row);
    }
  }

I get an exception:

Exception in thread "main" java.lang.RuntimeException: Invalid Union index (-40); union only has 2 types
        at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:196)
        at test.AvroReadToJsonNode.main(AvroReadToJsonNode.java:33)
Caused by: java.io.IOException: Invalid Union index (-40); union only has 2 types
        at com.fasterxml.jackson.dataformat.avro.deser.ScalarDecoder$ScalarUnionDecoder$FR._checkIndex(ScalarDecoder.java:422)
        at com.fasterxml.jackson.dataformat.avro.deser.ScalarDecoder$ScalarUnionDecoder$FR.readValue(ScalarDecoder.java:412)
        at com.fasterxml.jackson.dataformat.avro.deser.RecordReader$Std.nextToken(RecordReader.java:134)
        at com.fasterxml.jackson.dataformat.avro.deser.AvroParserImpl.nextToken(AvroParserImpl.java:98)
        at com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:249)
        at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:68)
        at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:15)
        at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:277)
        at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:192)

The schema looks like this:

{
  "type" : "record",
  "name" : "test",
  "namespace" : "test.test.avro",
  "doc" : "",
  "fields" : [ {
    "name" : "some_string",
    "type" : [ "null", "string"]
  } ]
}

And I generated data from the schema using avrotools:

avrotools random --schema-file test.avro.schema --count 100 test.avro

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions