简体   繁体   中英

Ignore JSON tags when marshalling

I am getting JSON data from an external source. The field names in this JSON are not something I want to carry with me, so I am converting them to names that make sense to me using the json:"originalname" tags.

When I marshal such an object back to JSON, I naturally get the ugly (original) names again.

Is there a way to ignore tags when marshalling? Or a way to specify a different name for marshall and unmarshall?

To clarify, I have prepared an example in the playground and pasted the same code below.

Thanks in advance.

package main

import (
    "encoding/json"
    "fmt"
)

type Band struct {
    Name   string `json:"bandname"`
    Albums int    `json:"albumcount"`
}

func main() {
    // JSON -> Object
    data := []byte(`{"bandname": "AC/DC","albumcount": 10}`)
    band := &Band{}
    json.Unmarshal(data, band)

    // Object -> JSON
    str, _ := json.Marshal(band)
    fmt.Println("Actual Result: ", string(str))
    fmt.Println("Desired Result:", `{"Name": "AC/DC","Albums": 10}`)

    // Output:
    // Actual Result:  {"bandname":"AC/DC","albumcount":10}
    // Desired Result: {"Name": "AC/DC","Albums": 10}
}

You could implement

type Marshaler interface {
        MarshalJSON() ([]byte, error)
}

from the standard library's encoding/json package. Example:

type Band struct {
    Name   string `json:"bandname"`
    Albums int    `json:"albumcount"`
}

func (b Band) MarshalJSON() ([]byte, error) {
    n, _ := json.Marshal(b.Name)
    a, _ := json.Marshal(b.Albums)
    return []byte(`{"Name":` + string(n) + `,"Albums":` + string(a) + `}`)
}

It's admittedly not a very nice solution, though.

As a generic solution, you could use reflection to create a new type that removes the json tags and then marshall that.

func getVariantStructValue(v reflect.Value, t reflect.Type) reflect.Value {
    sf := make([]reflect.StructField, 0)
    for i := 0; i < t.NumField(); i++ {
        sf = append(sf, t.Field(i))

        if t.Field(i).Tag.Get("json") != "" {
            sf[i].Tag = ``
        }
    }
    newType := reflect.StructOf(sf)
    return v.Convert(newType)
}

func MarshalIgnoreTags(obj interface{}) ([]byte, error) {
    value := reflect.ValueOf(obj)
    t := value.Type()
    newValue := getVariantStructValue(value, t)
    return json.Marshal(newValue.Interface())
}

And you would just call it using:

str, _ := MarshalIgnoreTags(band)

Doing the opposite is a little trickier (ignore tags when unmarshalling JSON), but possible with mapstructure :

func UnmarshalIgnoreTags(data []byte, obj interface{}) error {
    rv := reflect.ValueOf(obj)
    if rv.Kind() != reflect.Ptr || rv.IsNil() {
        return errors.New("unmarshal destination obj must be a non-nil pointer")
    }

    value := reflect.Indirect(rv)
    t := value.Type()

    newValue := getVariantStructValue(value, t)
    i := newValue.Interface()
    err := json.Unmarshal(data, &i)
    if err == nil {
        // We use mapstructure because i is of type map[string]interface{} and it's the easiest way to convert back to struct type
        // See: https://stackoverflow.com/a/38939459/2516916
        mapstructure.Decode(i, obj)
    }

    return err
}

See playground here: https://play.golang.org/p/XVYGigM71Cf

You could also use a library as mentioned in this thread: https://stackoverflow.com/a/50966527/5649638

This will give you a structs like this:

type TestJson struct {
    Name string `json:"name" newtag:"newname"`
    Age  int    `json:"age" newtag:"newage"`
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM