dst8922 2018-03-31 06:43
浏览 79
已采纳

如何检查json是否与struct / struct字段匹配

Is there an easy way to check if each field of myStruct was mapped by using json.Unmarshal(jsonData, &myStruct).

The only way I could image is to define each field of a struct as pointer, otherwise you will always get back an initialized struct. So every jsonString that is an object (even an empty one {}) will return an initialized struct and you cannot tell if the json represented your struct.

The only solution I could think of is quite uncomfortable:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name *string `json:name`
    Age  *int    `json:age`
    Male *bool   `json:male`
}

func main() {
    var p *Person
    err := json.Unmarshal([]byte("{}"), &p)
    // handle parse error
    if err != nil {
        return
    }

    // handle json did not match error
    if p.Name == nil || p.Age == nil || p.Male == nil {
        return
    }

    // now use the fields with dereferencing and hope you did not forget a nil check
    fmt.Println("Hello " + *p.Name)
}

Maybe one could use a library like govalidator and use SetFieldsRequiredByDefault. But then you still have to execute the validation and still you are left with the whole pointer dereferencing for value retrieval and the risk of nil pointer.

What I would like is a function that returns my unmarshaled json as a struct or an error if the fields did not match. The only thing the golang json library offers is an option to fail on unknown fields but not to fail on missing fields.

Any idea?

  • 写回答

2条回答 默认 最新

  • dongluxin6711 2018-03-31 10:37
    关注

    Another way would be to implement your own json.Unmarshaler which uses reflection (similar to the default json unmarshaler):

    There are a few points to consider:

    • if speed is of great importance to you then you should write a benchmark to see how big the impact of the extra reflection is. I suspect its negligible but it can't hurt to write a small go benchmark to get some numbers.
    • the stdlib will unmarshal all numbers in your json input into floats. So if you use reflection to set integer fields then you need to provide the corresponding conversion yourself (see TODO in example below)
    • the json.Decoder.DisallowUnknownFields function will not work as expected with your type. You need to implement this yourself (see example below)
    • if you decide to take this approach you will make your code more complex and thus harder to understand and maintain. Are you actually sure you must know if fields are omitted? Maybe you can refactor your fields to make good usage of the zero values?

    Here a fully executable test of this approach:

    package sandbox
    
    import (
        "encoding/json"
        "errors"
        "reflect"
        "strings"
        "testing"
    )
    
    type Person struct {
        Name string
        City string
    }
    
    func (p *Person) UnmarshalJSON(data []byte) error {
        var m map[string]interface{}
        err := json.Unmarshal(data, &m)
        if err != nil {
            return err
        }
    
        v := reflect.ValueOf(p).Elem()
        t := v.Type()
    
        var missing []string
        for i := 0; i < t.NumField(); i++ {
            field := t.Field(i)
            val, ok := m[field.Name]
            delete(m, field.Name)
            if !ok {
                missing = append(missing, field.Name)
                continue
            }
    
            switch field.Type.Kind() {
            // TODO: if the field is an integer you need to transform the val from float
            default:
                v.Field(i).Set(reflect.ValueOf(val))
            }
        }
    
        if len(missing) > 0 {
            return errors.New("missing fields: " + strings.Join(missing, ", "))
        }
    
        if len(m) > 0 {
            extra := make([]string, 0, len(m))
            for field := range m {
                extra = append(extra, field)
            }
            // TODO: consider sorting the output to get deterministic errors:
            // sort.Strings(extra)
            return errors.New("unknown fields: " + strings.Join(extra, ", "))
        }
    
        return nil
    }
    
    func TestJSONDecoder(t *testing.T) {
        cases := map[string]struct {
            in       string
            err      string
            expected Person
        }{
            "Empty object": {
                in:       `{}`,
                err:      "missing fields: Name, City",
                expected: Person{},
            },
            "Name missing": {
                in:       `{"City": "Berlin"}`,
                err:      "missing fields: Name",
                expected: Person{City: "Berlin"},
            },
            "Age missing": {
                in:       `{"Name": "Friedrich"}`,
                err:      "missing fields: City",
                expected: Person{Name: "Friedrich"},
            },
            "Unknown field": {
                in:       `{"Name": "Friedrich", "City": "Berlin", "Test": true}`,
                err:      "unknown fields: Test",
                expected: Person{Name: "Friedrich", City: "Berlin"},
            },
            "OK": {
                in:       `{"Name": "Friedrich", "City": "Berlin"}`,
                expected: Person{Name: "Friedrich", City: "Berlin"},
            },
        }
    
        for name, c := range cases {
            t.Run(name, func(t *testing.T) {
                var actual Person
                r := strings.NewReader(c.in)
                err := json.NewDecoder(r).Decode(&actual)
                switch {
                case err != nil && c.err == "":
                    t.Errorf("Expected no error but go %v", err)
                case err == nil && c.err != "":
                    t.Errorf("Did not return expected error %v", c.err)
                case err != nil && err.Error() != c.err:
                    t.Errorf("Expected error %q but got %v", c.err, err)
                }
    
                if !reflect.DeepEqual(c.expected, actual) {
                    t.Errorf("
    Want: %+v
    Got:  %+v", c.expected, actual)
                }
            })
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)