登录
首页 >  Golang >  Go问答

如何将输入转换为符合条件的对象并以 JSON 字符串形式返回

来源:stackoverflow

时间:2024-02-17 13:09:25 217浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何将输入转换为符合条件的对象并以 JSON 字符串形式返回》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

在这里,我想将 defaultresponse 作为字符串,但稍后在映射到任何 json 结构之前验证它是否是有效的 json。

可以在此处找到带有验证的完整代码: https://go.dev/play/p/kngnmj1qg3l

type AddEndpointRequest struct {
    Method            string `json:"method"`
    ContentType       int    `json:"contentType"`
    DefaultStatusCode int    `json:"defaultStatusCode"`
    DefaultResponse   string `json:"defaultResponse"`
}

我尝试了不同的选项,但没有一个有效

  1. 如果我通过这个:“defaultresponse”:{“title”:“买奶酪和面包当早餐。”} 收到错误:json:无法将对象解组到字符串类型的 go 结构字段 addendpointrequest.defaultresponse

body := {"method":"get","contenttype":1,"defaultwaittimeinmillis":100,"defaultstatuscode":200,"defaultresponse":"[{"p":"k"}] "}

错误:对象键:值对后的字符“p”无效

3) body := {"method":"get","contenttype":1,"defaultwaittimeinmillis":100,"defaultstatuscode":200,"defaultresponse":"{"p":"k"}"} ./prog.go:21:117: 语法错误: 语句末尾出现意外的 {

  1. body := {"method":"get","contenttype":1,"defaultwaittimeinmillis":100,"defaultstatuscode":200,"defaultresponse":"{/"p/":/"k/ "}"} 错误:./prog.go:21:130: 语法错误:意外文字 "} 位于语句末尾

还有更多


正确答案


选项a:

将该字段声明为字符串。使用有效的 json 字符串作为文档中的字段值。请注意字符串中引号的转义。

type addendpointrequest struct {
    method            string          `json:"method"`
    contenttype       int             `json:"contenttype"`
    defaultstatuscode int             `json:"defaultstatuscode"`
    defaultresponse   string          `json:"defaultresponse"`
}
…
body := `{"method":"get","contenttype":1,"defaultwaittimeinmillis":100,"defaultstatuscode":200,"defaultresponse":"{\"p\":\"k\"}"}`

将字段转换为 [] 字节以进行解组:

err := json.unmarshal([]byte(request.defaultresponse), &data)

https://go.dev/play/p/ailgQQ3eQBH

选项b:

将该字段声明为 json.rawmessage。在文档中使用任何有效的 json。

type addendpointrequest struct {
    method            string          `json:"method"`
    contenttype       int             `json:"contenttype"`
    defaultstatuscode int             `json:"defaultstatuscode"`
    defaultresponse   json.rawmessage `json:"defaultresponse"`
}
…
body := `{"method":"get","contenttype":1,"defaultwaittimeinmillis":100,"defaultstatuscode":200,"defaultresponse":{"p":"k"}}`

json.unmarshal([]byte(body), &request) 的调用验证 json.rawmessage 字段。如果对 json.unmarshal 的调用未返回错误,则可以确保应用程序 addendpointrequest.defaultresponse 包含有效的 json。

像这样解组字段:

err := json.unmarshal(request.defaultresponse, &data)

https://go.dev/play/p/Xd_gWzJmvC_K

如果你想在 defaultresponse 中设置一个结构体,我认为这样做应该可行。

package main

import (
    "encoding/json"
    "errors"
    "fmt"
)

type AddEndpointRequest struct {
    Method            string `json:"method"`
    ContentType       int    `json:"contentType"`
    DefaultStatusCode int    `json:"defaultStatusCode"`
    DefaultResponse   string `json:"defaultResponse"`
}

func main() {

    body := `{"method":"GET","contentType":1,"defaultWaitTimeInMillis":100,"defaultStatusCode":200,"defaultResponse":{"title":"Buy cheese and bread for breakfast."}}`
    fmt.Println("Hello GO")

    err := validateBody(body)
    if err != nil {
        fmt.Println("erro102")
        fmt.Println(err)

    }
}

func validateBody(body string) error {
    var data map[string]interface{}
    err := json.Unmarshal([]byte(body), &data)
    if err != nil {
        return errors.New("invalid json body provided for the request")
    }

    fmt.Println("data===>", data)

    fmt.Println("defaultResponse===>", data["defaultResponse"].(map[string]interface{})["title"])

    return nil
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何将输入转换为符合条件的对象并以 JSON 字符串形式返回》文章吧,也可关注golang学习网公众号了解相关技术文章。

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