英文:
Serialising string arrays into json
问题
所以,我一直在使用Go语言进行调试,遇到了一个小问题。我有一些需要序列化为JSON的内容,格式如下:
{
"name" : "Steel",
"things" : ["Iron", "Carbon"]
}
用于保存这些内容的结构体如下:
type Message struct {
name string
things []string
}
我的代码如下:
func main() {
i := Message{"Steel", []string{"Iron", "Carbon"}}
fmt.Println(i)
b, _ := json.Marshal(i)
fmt.Printf("Json %v\n", b)
var o Message
json.Unmarshal(b, &o)
fmt.Printf("Decoded %v\n", o)
}
但是当我反序列化数据时,我得到了一个空的Message
,如下所示:
{Steel [Iron Carbon]}
Json [123 125]
Decoded { []}
我做错了什么?如何使其正常工作?
英文:
So, I've been tinkering with go and have a small problem. I have something that needs to be serialised into a json like so.
{
"name" : "Steel",
"things" : ["Iron", "Carbon"]
}
The struct to hold this looks like this.
type Message struct {
name string
things []string
}
and my code itself like this
func main() {
i := Message{"Steel", []string{"Iron", "Carbon"}}
fmt.Println(i);
b, _ := json.Marshal(i)
fmt.Printf(" Json %v\n", b);
var o Message;
json.Unmarshal(b, &o)
fmt.Printf(" Decoded %v\n", o);
}
When I deserialise the data though, I get back an empty Message
like so
{Steel [Iron Carbon]}
Json [123 125]
Decoded { []}
What am I doing wrong and how do I get it to work?
答案1
得分: 2
导出结构体的字段。未导出的字段不会被 encoding/json
包包含。
type Message struct {
Name string
Things []string
}
字段名应以大写字母开头(导出的)。
英文:
Export fields of the struct. Unexported fields are not included by encoding/json
type Message struct {
Name string
Things []string
}
The field names should begin with capital letters (Exported).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论