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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?