From d858578cb00931b723466a0755e895cbcd22fe47 Mon Sep 17 00:00:00 2001 From: "X. Wei" Date: Mon, 1 Oct 2012 06:02:54 -0700 Subject: [PATCH 1/2] Update 7.2.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正对于tag的描述 增加几个tag样例 --- 7.2.md | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/7.2.md b/7.2.md index f051608e..e87c802c 100644 --- a/7.2.md +++ b/7.2.md @@ -97,7 +97,7 @@ JSON(Javascript Object Notation)是一种轻量级的数据交换语言, fmt.Println(k, "is of a type I don't know how to handle") } } -通过上面的示例可以看到,通过interface{}与type assert的配合,我们就可以解析未知结构的JSON数了。 +通过上面的示例可以看到,通过interface{}与type assert的配合,我们就可以解析未知结构的JSON数了。 上面这个是官方提供的解决方案,其实很多时候我们通过类型断言,操作起来不是很方便,目前bitly公司开源了一个叫做`simplejson`的包,在处理未知结构体的JSON时相当方便,详细例子如下所示: @@ -171,12 +171,42 @@ JSON(Javascript Object Notation)是一种轻量级的数据交换语言, 针对JSON的输出,我们在定义struct tag的时候需要注意的几点是: -- tag中带有`"-"`,那么这个字段不会输出到JSON +- 字段的tag是`"-"`,那么这个字段不会输出到JSON - tag中带有自定义名称,那么这个自定义名称会出现在JSON的字段名中,例如上面例子中serverName -- tag中如果带有`"omitempty"`,那么如果该字段值为空,就不会输出到JSON串中 -- 如果字段类型是int,而tag中带有`"string"`,那么这个字段在输出到JSON的时候会把该字段对应的值转换成JSON字符串 +- tag中如果带有`"omitempty"`选项,那么如果该字段值为空,就不会输出到JSON串中 +- 如果字段类型是bool, string, int, int64等,而tag中带有`",string"`选项,那么这个字段在输出到JSON的时候会把该字段对应的值转换成JSON字符串 + + +举例来说: + + type Server struct { + // ID 不会导出到JSON中 + ID int `json:"-"` + + // ServerName 的值会进行二次JSON编码 + ServerName string `json:"serverName"` + ServerName2 string `json:"serverName2,string"` + + // 如果 ServerIP 为空,则不输出到JSON串中 + ServerIP string `json:"serverIP,omitempty"` + } + + s := Server { + ID: 3, + ServerName: `Go "1.0" `, + ServerName2: `Go "1.0" `, + ServerIP: ``, + } + b, _ := json.Marshal(s) + os.Stdout.Write(b) + +会输出以下内容: + + {"serverName":"Go \"1.0\" ","serverName2":"\"Go \\\"1.0\\\" \""} + + +在Marshal函数转换的过程中我们需要注意几点: -Marshal函数只有在转换成功的时候才会返回数据,在转换的过程中我们需要注意几点: - JSON对象只支持string作为key,所以要编码一个map,那么必须是map[string]T这种类型(T是Go语言中任意的类型) - Channel, complex和function是不能被编码成JSON的 From 5f421ff306aa7baae15ab34a4cb0a71d8d697967 Mon Sep 17 00:00:00 2001 From: "X. Wei" Date: Mon, 1 Oct 2012 06:09:15 -0700 Subject: [PATCH 2/2] Update 7.2.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更正刚才错误的修改 --- 7.2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/7.2.md b/7.2.md index e87c802c..5d657ce5 100644 --- a/7.2.md +++ b/7.2.md @@ -205,7 +205,7 @@ JSON(Javascript Object Notation)是一种轻量级的数据交换语言, {"serverName":"Go \"1.0\" ","serverName2":"\"Go \\\"1.0\\\" \""} -在Marshal函数转换的过程中我们需要注意几点: +Marshal函数只有在转换成功的时候才会返回数据,在转换的过程中我们需要注意几点: - JSON对象只支持string作为key,所以要编码一个map,那么必须是map[string]T这种类型(T是Go语言中任意的类型)