登录
首页 >  Golang >  Go问答

传递字符串数组作为 JSON 格式请求正文的方法

来源:stackoverflow

时间:2024-03-27 10:51:39 360浏览 收藏

在 Go 中,将字符串数组作为 JSON 格式请求正文传递时,可以使用 map[string]interface{} 类型的地图,该类型允许存储任意类型。或者,可以创建一个特定于请求的数据结构,以保持类型安全。此外,还可以将字符串数组一次封送,而不是对 map[string]string 进行封送。这通过编组字符串数组 []string 来实现。

问题内容

var tagsInput string

tagsInput = inputLine("Project tags [domain/topics etc, seprated by commas in input] :\n")

tags := strings.Split(tagsInput, ",")
parseTags, _ := json.Marshal(tags)
fmt.Println(tags)
fmt.Println(string(parseTags))
postBody, _ := json.Marshal(map[string]string{
    "name":   name,
    "desc":   desc,
    "status": status,
    "tags":   string(parseTags),
})

我需要一个数组作为标签,例如 ["golang"] 但它是一个字符串。


解决方案


您当前正在尝试对字符串 map[string]string 的映射进行 json 编组。您想要对 tags 字段执行的操作是编组字符串数组 []string

您的问题的答案是仅封送 tags 变量一次。快速解决方案是将您的地图设为 interface{} 类型的地图。它允许您在映射中存储任意类型,这些类型将被正确地 json 封送:

https://play.golang.org/p/7D-wy7rQ8o_6

input := "golang, elixir, python, java"
    tags := strings.split(input, ",")
    
    postbody, _ := json.marshal(map[string]interface{}{
        "name":   name,
        "desc":   desc,
        "status": status,
        "tags":   tags,
    })

缺点是你失去了类型安全。现在每个字段都可以是任何内容。更好的方法是为此请求创建一个数据结构:

https://play.golang.org/p/wTbrXH0HXoG

type Request struct {
    Name        string   `json:"name"`
    Description string   `json:"description"`
    Status      string   `json:"status"`
    Tags        []string `json:"tags"`
}

input := "golang, elixir, python, java"
tags := strings.Split(input, ",")

postBody, _ := json.Marshal(Request{
    Name:        name,
    Description: desc,
    Status:      status,
    Tags:        tags,
})

好了,本文到此结束,带大家了解了《传递字符串数组作为 JSON 格式请求正文的方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>