How do I unmarshal a JSON to a struct which contains 2 fields (UserName and Name) containing the same JSON Tag Name (name)?
package main
import (
"encoding/json"
"fmt"
)
type User struct {
UserName string `json:"name,omitempty"`
Name string `json:"name,omitempty"`
}
func main() {
data := []byte(`
{
"name":"kishore"
}
`)
user := &User{}
err := json.Unmarshal(data, &user)
if err != nil {
panic(err)
}
fmt.Printf("value of user : %+v\n", user)
}
Actual Output:
value of user : &{UserName: Name:}
Expected Output:
value of user : &{UserName:kishore Name:kishore}
How do I get the UserName and Name field Populated with kishore?
When I look at the source code of Json I see they discard if 2 top level fields have same tag name. But this comment in code made me think if there is a way to tag both either both tagged or neither tagged
func dominantField(fields []field) (field, bool) {
// The fields are sorted in increasing index-length order, then by presence of tag.
// That means that the first field is the dominant one. We need only check
// for error cases: two fields at top level, either both tagged or neither tagged.
if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tag == fields[1].tag {
return field{}, false
}
return fields[0], true
}
Playground Link : https://play.golang.org/p/TN9IQ8lFR6a
Unmarshalsays: "To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal", andMarshalsays: "If there is exactly one field (tagged or not according to the first rule), that is selected...Otherwise there are multiple fields, and all are ignored"encoding/jsondoes not support multiple struct fields for the same JSON key. You'll have to do this yourself, either by implementingUnmarshalJSON, or by unmarshaling into one field and copying to the other yourself. However, I would very very strongly recommend a thorough code review, because there should be no situation where you actually need the described behavior if the design is correct.