User Tools

Site Tools


unm.go
/*
 * Author, Copyright: Oleg Borodin <onborodin@gmail.com>
 */
 
 
package main
 
import (
    "encoding/json"
    //"errors"
    "fmt"
    "reflect"
)
 
type InvoicePayload struct {
        InvoiceUID  string `json:"invoiceUID"`
        InvoiceRef  string `json:"invoiceRef"`
}
 
type Invoice struct {
    Payload []InvoicePayload
}
 
func (this Invoice) MarshalJSON() ([]byte, error) {
    json, err := json.Marshal(this.Payload)
    return json, err
}
 
func (this *Invoice) UnmarshalJSON(data []byte) error {
    var ref interface{}
    err := json.Unmarshal(data, &ref)
    if err != nil {
        return err
    }
 
    v := reflect.ValueOf(ref)
 
    s := InvoicePayload{}
    switch v.Kind() {
        case reflect.Map:
            for _, key := range v.MapKeys() {
                value := v.MapIndex(key)
                fmt.Println(key.Interface(), value.Interface())
 
 
                t := reflect.TypeOf(s)
                ptr := reflect.ValueOf(&s)
                elem := ptr.Elem()
 
 
                switch t.Kind() {
                    case reflect.Struct:
 
                        for i := 0; i < t.NumField(); i++ {
                            tagValue := t.Field(i).Tag.Get("json")
                            fieldName := t.Field(i).Name
 
                            keyName := key.Interface()
                            value := value.Interface()
 
                            if tagValue == keyName {
 
                                fmt.Println("match:", key.Interface())
                                fmt.Println("filedName:", fieldName)
 
                                f := elem.FieldByName(fieldName)
                                if f.IsValid() && f.CanSet() {
                                    if f.Kind() == reflect.String {
                                        f.SetString(value.(string))
                                        //f.SetString("xxx")
                                    }
                                }
                            }
                        }
 
                }
 
            }
            this.Payload = append(this.Payload, s)
        default:
            return nil
    }
    return nil
}
 
func main() {
    j := []byte(`{ "invoiceUID": "0000-0001", "invoiceRef": "0000-0002" }`)
    var i Invoice
    err := json.Unmarshal(j, &i)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(i)
    j, err = json.MarshalIndent(i, "", "    ")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(j))
}
$ go run invoice_map_v2.go
invoiceUID 0000-0001
match: invoiceUID
filedName: InvoiceUID
invoiceRef 0000-0002
match: invoiceRef
filedName: InvoiceRef
{[{0000-0001 0000-0002}]}
[
    {
        "invoiceUID": "0000-0001",
        "invoiceRef": "0000-0002"
    }
]