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

如何在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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀