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 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多