gpt4 book ai didi

json - 在 Go 中从 POST 请求解码 JSON 失败

转载 作者:IT王子 更新时间:2023-10-29 02:33:36 26 4
gpt4 key购买 nike

我使用如下 JSON 数据向我的 Go 应用程序发送 POST 请求:

var test = {text: "Lorem ipsum dolor sit amet"};

$.ajax({
url: "/api/test/add",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(test),
success: function(data) {
// ...
},
error: function(xhr, status, err) {
// ...
}
});

在我的 Go 应用程序中,我有以下代码(使用 vestigo ):

type Test struct {
id int
text string
}

func apiAddTestHandler(w http.ResponseWriter, r *http.Request) {
r_body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}

// Here looks like everything is ok because I get
// {"text": "Lorem ipsum dolor sit amet"} if I try
// to convert r_body to string (string(r_body)).

var test Test
err = json.Unmarshal(r_body, &test)
if err != nil {
panic(err)
}

// Process test struct below, but here I get
// {id:0 text:} if I try to use or print the value
// of test (fmt.Printf("%+v\n", test)).
}

func main() {
router := vestigo.NewRouter()
router.Post("/api/test/add", apiAddTestHandler)

err := http.ListenAndServe(":3000", router)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

问题是,在 apiAddTestHandler() 中我无法使用解码的 JSON 数据“填充”测试结构。评论中有更多信息。我也尝试了以下代码片段但没有成功:

decoder := json.NewDecoder(r.Body)
var test Test
err := decoder.Decode(&test)
if err != nil {
panic(err)
}

问题是什么?

最佳答案

来自Unmarshal documentation (重点是我的):

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. Unmarshal will only set exported fields of the struct.

您需要更改结构中的字段定义:

type Test struct {
ID int
Text string
}

请注意,根据 Golang naming conventions,我使用 ID 而不是 Id .

关于json - 在 Go 中从 POST 请求解码 JSON 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com