如何在Go中使用非必需的JSON参数? [英] How to work with non required JSON parameters in Go?

查看:97
本文介绍了如何在Go中使用非必需的JSON参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Go中使用rest API,我希望用户传递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"`

但是并不总是必须使用它们,例如,用户只能通过Offset而忽略其他用户.他甚至可以发送0个参数.我该怎么办?

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?

推荐答案

从JSON文本解组值时,

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.

要注意的一件事是,如果JSON文本中缺少字段,则json包将不会更改相应的Go字段,因此,如果您以"fresh"开头,则

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.

大多数时候,这足以检测字段的存在或不存在(在JSON中),例如,如果在Go结构中您具有类型为stringSortBy字段(如果JSON中缺少此字段) ,它将保留为空的string:"".

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: "".

如果零值有用且有效,那么您可以转向使用指针.例如,如果在您的应用程序中空的string将是有效的SortBy值,则可以将该字段声明为指针:*string.并且在这种情况下,如果JSON文本中缺少该字符,它将保留nil,这是任何指针类型的零值.

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.

请参见以下示例:

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\n", d, err)

    d, err = Data{}, nil
    err = json.Unmarshal([]byte(`{"I":1}`), &d)
    fmt.Printf("%#v %v\n", d, err)

    d, err = Data{}, nil
    err = json.Unmarshal([]byte(`{"S":"abc"}`), &d)
    fmt.Printf("%#v %v\n", d, err)
}

输出(在游乐场上尝试):

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>

这篇关于如何在Go中使用非必需的JSON参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆