将Go中的JSON转换为结构体时出现错误。

huangapple go评论90阅读模式
英文:

Error while converting json to struct from Go

问题

func MakeMap(w http.ResponseWriter, r *http.Request) {
// userInfo := context.Get(r, "userInfo").(model.User)
type _getData struct {
Title string json:"title"
Tag []string json:"tag"
}
var getData _getData
err := json.NewDecoder(r.Body).Decode(&getData)
if err != nil {
panic(err.Error())
}
fmt.Print(getData)
}
当我运行上面的代码时,我得到以下错误信息:
2021/08/24 13:56:54 http: panic serving 127.0.0.1:50619: 运行时错误: 无效的内存地址或空指针解引用
goroutine 23 [running]:
net/http.(*conn).serve.func1(0x140001e9180)
/usr/local/go/src/net/http/server.go:1824 +0x108
panic(0x10505b860, 0x10522f240)
/usr/local/go/src/runtime/panic.go:971 +0x3f4
traveling/controller/mapController.MakeMap(0x1050b5630, 0x140001f40e0, 0x1400018aa00)
/Users/choeyunseog/traveling/traveling/controller/mapController/mapController.go:20 +0x3c
我刚开始学习,不确定为什么会出现这个问题,请帮忙解决。

当我将代码第20行修改为以下内容时,我得到以下错误信息:
2021/08/24 14:16:44 http: panic serving 127.0.0.1:51396: 数字文字中的无效字符'-'
goroutine 23 [running]:
net/http.(*conn).serve.func1(0x140001e9360)
/usr/local/go/src/net/http/server.go:1824 +0x108
panic(0x100d85d00, 0x14000206070)
/usr/local/go/src/runtime/panic.go:971 +0x3f4
traveling/controller/mapController.MakeMap(0x100df1630, 0x140001f40e0, 0x1400018aa00)
/Users/choeyunseog/traveling/traveling/controller/mapController/mapController.go:24 +0x194
net/http.HandlerFunc.ServeHTTP(0x100de75d8, 0x100df1630, 0x140001f40e0, 0x1400018aa00)
/usr/local/go/src/net/http/server.go:2069 +0x40

英文:
 func MakeMap(w http.ResponseWriter, r *http.Request) {
	// userInfo := context.Get(r, "userInfo").(model.User)
	type _getData struct {
		Title string   `json:"title"`
		Tag   []string `json:"tag"`
	}
	var getData _getData
	err := json.NewDecoder(r.Body).Decode(&getData)
	if err != nil {
		panic(err.Error())
	}
	fmt.Print(getData)

}

When I run the above code, I get the following error

2021/08/24 13:56:54 http: panic serving 127.0.0.1:50619: runtime error: invalid memory address or nil pointer dereference
goroutine 23 [running]:
net/http.(*conn).serve.func1(0x140001e9180)
        /usr/local/go/src/net/http/server.go:1824 +0x108
panic(0x10505b860, 0x10522f240)
        /usr/local/go/src/runtime/panic.go:971 +0x3f4
traveling/controller/mapController.MakeMap(0x1050b5630, 0x140001f40e0, 0x1400018aa00)
/Users/choeyunseog/traveling/traveling/controller/mapController/mapController.go:20 +0x3c

I've just started studying, I'm not sure why I'm having this problem, please help

将Go中的JSON转换为结构体时出现错误。

err := json.NewDecoder(r.Body).Decode(&getData) 

I get the following error when i change code line 20 like above

 2021/08/24 14:16:44 http: panic serving 127.0.0.1:51396: invalid character '-' in numeric literal
goroutine 23 [running]:
net/http.(*conn).serve.func1(0x140001e9360)
        /usr/local/go/src/net/http/server.go:1824 +0x108
panic(0x100d85d00, 0x14000206070)
        /usr/local/go/src/runtime/panic.go:971 +0x3f4
traveling/controller/mapController.MakeMap(0x100df1630, 0x140001f40e0, 0x1400018aa00)
        /Users/choeyunseog/traveling/traveling/controller/mapController/mapController.go:24 +0x194
net/http.HandlerFunc.ServeHTTP(0x100de75d8, 0x100df1630, 0x140001f40e0, 0x1400018aa00)
        /usr/local/go/src/net/http/server.go:2069 +0x40

答案1

得分: 1

要从POST/PUT/PATCH请求的主体中获取多部分表单数据,您可以使用ParseMultipartForm方法解析主体,然后通过PostForm字段访问数据。或者,您可以使用FormValue只获取与表单字段关联的第一个值。

maxMemory := 32<<20
if err := r.ParseMultipartForm(maxMemory); err != nil {
    panic(err)
}

fmt.Println(_getData{
    Title: r.FormValue("title"), // FormValue返回字符串
    Tag:   r.PostForm["tag[]"],  // PostForm是一个[]string的映射
})
英文:

To get the multipart form data from a POST/PUT/PATCH request's body you can use the ParseMultipartForm method to parse the body and then access the data through the PostForm field. Or you can use FormValue to get just the first value associated with the form's field.

maxMemory := 32&lt;&lt;20
if err := r.ParseMultipartForm(maxMemory); err != nil {
    panic(err)
}

fmt.Println(_getData{
    Title: r.FormValue(&quot;title&quot;), // FormValue returns string
    Tag:   r.PostForm[&quot;tag[]&quot;],  // PostForm is a map of []string
})

答案2

得分: 0

您可以使用包github.com/senpathi/paramex将表单数据解析为带有注释结构的JSON。结构字段必须使用param关键字进行注释,并且标签名称是表单数据的键。

您的结构应如下所示。

type _getData struct {
    Title string   `param:"title"`
    Tag   []string `param:"tag[]"`
}

这是您在问题中提到的Postman请求的更新的MakeMap处理程序函数。

func MakeMap(w http.ResponseWriter, r *http.Request) {
    // userInfo := context.Get(r, "userInfo").(model.User)
    type _getData struct {
        Title string   `param:"title"`
        Tag   []string `param:"tag[]"`
    }

    // 这是必需的,因为您从Postman以multipart/form-data形式发送数据
    maxMemory := 32<<20
    if err := r.ParseMultipartForm(int64(maxMemory)); err != nil {
        panic(err)
    }

    var getData _getData

    extractor := paramex.NewParamExtractor()
    err := extractor.ExtractForms(&getData, r)
    if err != nil {
        panic(err.Error())
    }

    fmt.Print(getData)
    //输出:{defaultMap [travelling travelling2]}
}
英文:

You can use to parse form data into json like annotated struct using package github.com/senpathi/paramex. Struct fields must be annotated with param keyword and tag name is key of the form data.

your struct should be as below.

type _getData struct {
		Title string   `param:&quot;title&quot;`
		Tag   []string `param:&quot;tag[]&quot;`
	}

This is the updated MakeMap handler function for your postman request mentioned in the question

func MakeMap(w http.ResponseWriter, r *http.Request) {
	// userInfo := context.Get(r, &quot;userInfo&quot;).(model.User)
	type _getData struct {
		Title string   `param:&quot;title&quot;`
		Tag   []string `param:&quot;tag[]&quot;`
	}

	// this needed because u send data from Postman as multipart/form-data
	maxMemory := 32&lt;&lt;20
	if err := r.ParseMultipartForm(int64(maxMemory)); err != nil {
		panic(err)
	}

	var getData _getData

	extractor := paramex.NewParamExtractor()
	err := extractor.ExtractForms(&amp;getData, r)
	if err != nil {
		panic(err.Error())
	}

	fmt.Print(getData)
	//Output: {defaultMap [travelling travelling2]}
}

huangapple
  • 本文由 发表于 2021年8月24日 13:08:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/68902041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定