lundi 30 janvier 2023

How to set new tag value of nested struct using reflection

I have this structures:

type Library struct {
    Book            Book           
    Owner           Owner           
    Editorial.       Editorial
}

type Book struct {
    ID             string           `json:"id"`
    Title          string           `json:"title"`
    Description    string           `json:"description"`
    Category       string           `json:"category"`
} 

My code changes the json tag of the Book structure (autogenerated). How can I assign the new tag value ("categoryID") to the final structure, as in order to set new value I had to create a new variable "sub". How can I assign "sub" to f ?

func renameTags(p interface{}) any {
    rv := reflect.ValueOf(p)
    rt := rv.Elem().Type()
    fields := make([]reflect.StructField, rt.NumField())
    for i := range fields {
        f := rt.Field(i)
        if f.Type.Kind() == reflect.Struct && f.Type.Name() == "Book" {
            sub := f.Type.Field(13)
            sub.Tag = reflect.StructTag(`json:"` + "categoryID" + `"`)
            
        }

        fields[i] = f
    }

    st := reflect.ValueOf(fields)
    x := st.Interface()
    return x 
}

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire