将字符串数组序列化为 JSON。

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

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).

huangapple
  • 本文由 发表于 2016年3月18日 14:26:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/36077568.html
匿名

发表评论

匿名网友

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

确定