goavro
goavro copied to clipboard
Can't decode nested field which parent field could be null or record
I have next code:
package main
import (
"log"
"github.com/linkedin/goavro/v2"
)
const schema = `{
"type": "record",
"name": "Payload",
"fields": [
{
"name": "image",
"default": "null",
"type": [
"null",
{
"type": "record",
"name": "Image",
"fields": [
{
"name": "url",
"type": "string"
},
{
"name": "caption",
"type": "string",
"default": "undefined"
}
]
}
]
}
]
}
`
func main() {
codec, err := goavro.NewCodec(schema)
if err != nil {
println("schema is wrong")
log.Fatalln(err)
}
str := `{"image": {"caption": "asd"}}`
a, b, err := codec.NativeFromTextual([]byte(str))
if err != nil {
println(err.Error())
} else {
println(string(b))
println(a)
}
}
Image is optional field: it could be null or contain some fields (url and caption).
Instead of successful parsing of JSON i receving next error message: cannot decode textual record "SendPayload": cannot decode textual union: cannot decode textual map: cannot determine codec: "caption" for key: "image"
.
Problem is that avro schema contains image.caption
field. I tried sending image with caption, url and both, but problem persists.
This works:
str := `{"image": { "Image" : {"caption": "asd", "url": "URL"}}}`
When using union type, target type should be specified