英文:
Why do these golang JSON Unmarshal examples behave differently?
问题
我对以下行为感到困惑,并试图弄清楚该怎么做。有人可以解释一下为什么它们的行为不同吗?为什么web_url
没有被读入Bar.Url
中?
package main
import (
"encoding/json"
"fmt"
"testing"
)
type Foo struct {
Web_url string
}
type Bar struct {
Url string `json:'web_url'`
}
func TestJson(t *testing.T) {
j := []byte(`{"web_url":"xyz"}`)
f := &Foo{}
err := json.Unmarshal(j, f)
fmt.Printf("err: %v, f: %+v\n", err, f)
b := &Bar{}
err = json.Unmarshal(j, b)
fmt.Printf("err: %v, b: %+v\n", err, b)
}
结果...
go test -v -run TestJson
=== RUN TestJson
err: <nil>, f: &{Web_url:xyz}
err: <nil>, b: &{Url:}
--- PASS: TestJson (0.00s)
PASS
ok gitlabsr.nuq.ion.nokia.net/sr/linux/gitlab-tools/internal/junk
英文:
I'm puzzled by the following behavior and I'm trying to figure out what to do about it. Can anyone please explain to me why these behave differently? Why isn't web_url
read into Bar.Url
?
package main
import (
"encoding/json"
"fmt"
"testing"
)
type Foo struct {
Web_url string
}
type Bar struct {
Url string `json:'web_url'`
}
func TestJson(t *testing.T) {
j := []byte(`{"web_url":"xyz"}`)
f := &Foo{}
err := json.Unmarshal(j, f)
fmt.Printf("err: %v, f: %+v\n", err, f)
b := &Bar{}
err = json.Unmarshal(j, b)
fmt.Printf("err: %v, b: %+v\n", err, b)
}
Results...
go test -v -run TestJson
=== RUN TestJson
err: <nil>, f: &{Web_url:xyz}
err: <nil>, b: &{Url:}
--- PASS: TestJson (0.00s)
PASS
ok gitlabsr.nuq.ion.nokia.net/sr/linux/gitlab-tools/internal/junk
答案1
得分: 4
在结构标签定义中使用单引号引起了这个错误。
package main
import (
"encoding/json"
"fmt"
"testing"
)
type Foo struct {
Web_url string
}
type Bar struct {
Url string `json:"web_url"`
}
func TestJson(t *testing.T) {
j := []byte(`{"web_url":"xyz"}`)
f := &Foo{}
err := json.Unmarshal(j, f)
fmt.Printf("err: %v, f: %+v\n", err, f)
b := &Bar{}
err = json.Unmarshal(j, b)
fmt.Printf("err: %v, b: %+v\n", err, b)
}
在Bar
结构体中,使用单引号'
代替双引号"
引起了错误。应该使用双引号来定义结构标签,如json:"web_url"
。
英文:
Using single quotes in struct tag definition caused this error.
package main
import (
"encoding/json"
"fmt"
"testing"
)
type Foo struct {
Web_url string
}
type Bar struct {
Url string `json:"web_url"`
}
func TestJson(t *testing.T) {
j := []byte(`{"web_url":"xyz"}`)
f := &Foo{}
err := json.Unmarshal(j, f)
fmt.Printf("err: %v, f: %+v\n", err, f)
b := &Bar{}
err = json.Unmarshal(j, b)
fmt.Printf("err: %v, b: %+v\n", err, b)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论