duanchu7271 2016-09-13 08:31
浏览 501
已采纳

如何在Go中使用非必需的JSON参数?

Hi I am working on a rest API in Go and I want the user to pass JSON parameters:

Offset int64  `json:"offset"`
Limit  int64  `json:"limit"`
SortBy string `json:"sortby"`
Asc    bool   `json:"asc"`
Username   string `json:"username"`
First_Name string `json:"first_name"`
Last_Name  string `json:"last_name"`
Status     string `json:"status"`

But they are not always required so for example a user can pass only Offset and ignore the others. He can even send 0 parameters. How can I do this?

  • 写回答

1条回答 默认 最新

  • dongyinglan8707 2016-09-13 08:48
    关注

    When unmarshalling a value from JSON text, the json package does not require that all fields to be present in JSON, nor that all JSON fields have a matching Go field.

    So you don't have anything special to do, just unmarshal what you have to a Go value what you want or may want.

    One thing to note is that if a field is missing in the JSON text, the json package will not change the corresponding Go field, so if you start with a "fresh", zero value, the field will be left with the zero value of its type.

    Most of the time this is enough to detect the presence or absence of a field (in JSON), for example if in the Go struct you have a SortBy field of type string, if this is missing in JSON, it will remain the empty string: "".

    If the zero value is something useful and valid, then you may turn to use pointers. For example if in your application the empty string would be a valid SortBy value, you may declare this field to be a pointer: *string. And in this case if it's missing in the JSON text, it will remain nil, the zero value for any pointer type.

    See this example:

    type Data struct {
        I int
        S string
        P *string
    }
    
    func main() {
        var d Data
        var err error
    
        d, err = Data{}, nil
        err = json.Unmarshal([]byte(`{"I":1, "S":"sv", "P":"pv"}`), &d)
        fmt.Printf("%#v %v
    ", d, err)
    
        d, err = Data{}, nil
        err = json.Unmarshal([]byte(`{"I":1}`), &d)
        fmt.Printf("%#v %v
    ", d, err)
    
        d, err = Data{}, nil
        err = json.Unmarshal([]byte(`{"S":"abc"}`), &d)
        fmt.Printf("%#v %v
    ", d, err)
    }
    

    Output (try it on the Go Playground):

    main.Data{I:1, S:"sv", P:(*string)(0x1050a150)} <nil>
    main.Data{I:1, S:"", P:(*string)(nil)} <nil>
    main.Data{I:0, S:"abc", P:(*string)(nil)} <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大