我正在玩Go并且难以理解为什么json编码和解码对我不起作用
我想我几乎逐字地复制了这些例子,但是输出结果表明编组和解组都没有返回任何数据.他们也没有给出错误.
任何人都可以暗示我哪里出错了?
我的示例代码:去游乐场
package main
import "fmt"
import "encoding/json"
type testStruct struct {
clip string `json:"clip"`
}
func main() {
//unmarshal test
var testJson = "{\"clip\":\"test\"}"
var t testStruct
var jsonData = []byte(testJson)
err := json.Unmarshal(jsonData, &t)
if err != nil {
fmt.Printf("There was an error decoding the json. err = %s", err)
return
}
fmt.Printf("contents of decoded json is: %#v\r\n", t)
//marshal test
t.clip = "test2"
data, err := json.Marshal(&t)
if err != nil {
fmt.Printf("There was an error encoding the json. err = %s", err)
return
}
fmt.Printf("encoded json = %s\r\n", string(data))
}
Run Code Online (Sandbox Code Playgroud)
输出:
contents of decoded json is: main.testStruct{clip:""}
encoded json = {}
Run Code Online (Sandbox Code Playgroud)
在两个输出中我都希望看到解码或编码的json
pet*_*rSO 31
例如,
package main
import "fmt"
import "encoding/json"
type testStruct struct {
Clip string `json:"clip"`
}
func main() {
//unmarshal test
var testJson = "{\"clip\":\"test\"}"
var t testStruct
var jsonData = []byte(testJson)
err := json.Unmarshal(jsonData, &t)
if err != nil {
fmt.Printf("There was an error decoding the json. err = %s", err)
return
}
fmt.Printf("contents of decoded json is: %#v\r\n", t)
//marshal test
t.Clip = "test2"
data, err := json.Marshal(&t)
if err != nil {
fmt.Printf("There was an error encoding the json. err = %s", err)
return
}
fmt.Printf("encoded json = %s\r\n", string(data))
}
Run Code Online (Sandbox Code Playgroud)
输出:
contents of decoded json is: main.testStruct{Clip:"test"}
encoded json = {"clip":"test2"}
Run Code Online (Sandbox Code Playgroud)
操场:
http://play.golang.org/p/3XaVougMTE
导出结构字段.
type testStruct struct {
Clip string `json:"clip"`
}
Run Code Online (Sandbox Code Playgroud)
可以导出标识符以允许从另一个包访问它.如果两者都导出标识符:
- 标识符名称的第一个字符是Unicode大写字母(Unicode类"Lu"); 和
- 标识符在包块中声明,或者是字段名称或方法名称.
不导出所有其他标识符.
大写结构字段名称
type testStruct struct {
clip string `json:"clip"` // Wrong. Lowercase - other packages can't access it
}
Run Code Online (Sandbox Code Playgroud)
改成:
type testStruct struct {
Clip string `json:"clip"`
}
Run Code Online (Sandbox Code Playgroud)