golang json 序列化和反序列化

Spoony 53.6m2021-01-07845 次点击
```
package main

import (
"encoding/json"
"fmt"
"github.com/bitly/go-simplejson"
)

type personInfo struct {‌‌
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email" xml:"email"`
}

type personInfo1 struct {‌‌
Name string `json:"name"`
Email string `json:"email" xml:"email"`
C string
}

func main() {‌‌
// 创建数据
p := personInfo{‌‌Name: "Piao", Age: 10, Email: "xxx@163.com"}

// 序列化
data, _ := json.Marshal(&p)
fmt.Println(string(data))

// 反序列化
var p1 personInfo1
err := json.Unmarshal([]byte(data), &p1) // 貌似这种解析方法需要提前知道 json 结构
if err != nil {‌‌
fmt.Println("err: ", err)
} else {‌‌
fmt.Printf("name=%s, c=%s, email=%s\n", p1.Name, p1.C, p1.Email)
}
fmt.Printf("%+v\n", p1)

// 反序列化
res, err := simplejson.NewJson([]byte(data))
if err != nil {‌‌
fmt.Println("err: ", err)
} else {‌‌
fmt.Printf("%+v\n", res)
}
}
```

运行结果

```
test go run main.go
{‌"name":"Piao","age":10,"email":"xxx@163.com"}
name=Piao, c=, email=xxx@163.com
{‌Name:Piao Email:xxx@163.com C:}
&{‌data:map[name:Piao age:10 email:xxx@163.com]}
```

https://www.cnblogs.com/williamjie/p/9927281.html
收藏 ♥ 感谢
Spoony 小组长 2021-01-09 
Struct fields must start with upper case letter (exported) for the JSON package to see their value.

struct A struct {‌
// Unexported struct fields are invisible to the JSON package.
// Export a field by starting it with an uppercase letter.
unexported string

// {‌"Exported": ""}
Exported string

// {‌"custom_name": ""}
CustomName string `json:"custom_name"`
}

The underlying reason for this requirement is that the JSON package uses reflect to inspect struct fields. Since reflect doesn't allow access to unexported struct fields, the JSON package can't see their value.

登录注册 后可回复。



GitHub