We need to use a custom unmarshaler for a struct nested in multiple other structs which don't require a custom unmarshaler. We have lots of structs similar to B
struct defined below (similar as in nesting A
). The code's output is true false 0
(expected true false 2
). Any ideas?
Go Playground example here.
package main
import (
"fmt"
"encoding/json"
)
type A struct {
X bool `json:"x"`
Y bool `json:"y"`
}
type B struct {
A
Z int `json:"z"`
}
func (a *A) UnmarshalJSON(bytes []byte) error {
var aa struct {
X string `json:"x"`
Y string `json:"y"`
}
json.Unmarshal(bytes, &aa)
a.X = aa.X == "123"
a.Y = aa.Y == "abc"
return nil
}
const myJSON = `{"x": "123", "y": "fff", "z": 2}`
func main() {
var b B
json.Unmarshal([]byte(myJSON), &b)
fmt.Print(b.X," ",b.Y," ",b.Z)
}
EDIT: question was marked as duplicate here but making A
an explicit field will make our API cluttered. Also after making A
an explicit field the result is false false 2
so it does not help at all.
A
but strings in the JSON? If you had matching types, then you wouldn't need to write an unmarshaller at all. Perhaps you can have a method forA
that returns the boolean value based on the string values that it already has? – Alliancejson
package. (assuming that you have contraints preventing you from matching the types in A and the JSON) – Alliance