Golang Multiple fields with same json tag name

Viewed 3424

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

2 Answers

This is actually a case of duplicate struct tags causing unmarshaller to ignore it. As per the official documentation - "3) Otherwise there are multiple fields, and all are ignored; no error occurs."

https://golang.org/pkg/encoding/json/

What you should probably do is "go vet" and see if your code has such issues.

type User struct {
    UserName string `json:"name,omitempty"`
    Name     string `json:"-"`
}

func (u *User) UnmarshalJSON(data []byte) error {
    type U User
    if err := json.Unmarshal(data, (*U)(u)); err != nil {
        return err
    }
    u.Name = u.UserName
    return nil
}

https://play.golang.org/p/PRuigiBfwWv

Related