Search code examples
jsonavro

Getting AvroTypeException: Unknown union branch


actually, I'm using AVRO to validate a json payload. I'm trying to declare a field (defined as record) optional but it does not work.

Schema

...
    {
      "name" : "buildarea",
      "type" : "com.data.Area",
      "type" : ["null","com.data.Area"],
      "default": null
    }
...

with Area defined as

{
  "type": "record",
  "namespace": "com.data",
  "name": "Area",
  "fields": [
        {
          "name": "start",
          "type": "double"
        },
        {
          "name": "end",
          "type": "double"
        }
    ]
 }

Json Example

If I define a not null value I get an exception: Unknown union branch start

"buildarea": {
   "start": 10.20,
   "end": 15
}

If I set the field as null e.g. "buildarea":null, I get an exception message: Expected record-start. Got VALUE_NULL

"buildarea": null

If I remove the optional spec in the schema i.e.

...
    {
      "name" : "buildarea",
      "type" : "com.data.Area"
    }
...

I must always define a not null "buildarea" object, which is not a correct expectation all the time i.e. buildarea maybe null.

Can anybody give me a hint to solve this?


Solution

  • you have to define your type only once to make it nullable, not twice. Like this

     {
      "name" : "buildarea",
      "type" : ["null","com.data.Area"],
      "default": null
     }