您的位置:首页 > Web前端 > JavaScript

golang基础知识之encoding/json package

2015-09-24 11:43 281 查看

golang基础知识之json

简介

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。可以去json.org 查看json标准的清晰定义。json package 是GO 语言官方提供的包,后续会提供开源实现json package的分析。

Encoding

func Marshal(v interface{}) ([]byte, error)

基本类型

bolB, _ := json.Marshal(true)    fmt.Println(string(bolB))    intB, _ := json.Marshal(1)    fmt.Println(string(intB))    fltB, _ := json.Marshal(2.34)    fmt.Println(string(fltB))

output:

true

1

2.34

"gopher"


自定义类型的序列化

type Response1 struct {    Page   int    Fruits []string}// The JSON package can automatically encode your// custom data types. It will only include exported// fields in the encoded output and will by default// use those names as the JSON keys.res1D := &Response1{    Page:   1,    Fruits: []string{"apple", "peach", "pear"}}res1B, _ := json.Marshal(res1D)fmt.Println(string(res1B))

只会将可外部访问的字段序列化到json里面去

能够以JSON形式呈现的数据结构才能被encode:

由于JSON 对象只支持strings 为key,Go map 类型必须以map[string]T的形式

Channel,复杂的和function无法被encode

循环的数据结构不支持

指针会按照指向的值被encode

Decoding

func Unmarshal(data []byte, v interface{}) errorb := []byte(`{"Name":"Bob","Food":"Pickle"}`)var m Messageerr := json.Unmarshal(b, &m)

对于结构中不是外部可访问的字段或者缺少的字段,反序列化会自动忽略该字段

使用interface{} 处理通用的json

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)var f interface{}err := json.Unmarshal(b, &f)b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)var f interface{}err := json.Unmarshal(b, &f)if err != nil {    panic(err)}m := f.(map[string]interface{})for k, v := range m {    switch vv := v.(type) {    case string:        fmt.Println(k, "is string", vv)    case int:        fmt.Println(k, "is int", vv)    case []interface{}:        fmt.Println(k, "is an array:")        for i, u := range vv {            fmt.Println(i, u)        }    default:        fmt.Println(k, "is of a type I don't know how to handle")    }}

Streaming Encoders and Decoders

package mainimport (    "encoding/json"    "log"    "os")func main() {dec := json.NewDecoder(os.Stdin)enc := json.NewEncoder(os.Stdout)for {    var v map[string]interface{}    if err := dec.Decode(&v); err != nil {        log.Println(err)        return    }    for k := range v {        if k != "Name" {            delete(v, k)        }    }    if err := enc.Encode(&v); err != nil {        log.Println(err)    }}}

参见:

http://blog.golang.org/json-and-gohttps://golang.org/pkg/encoding/json/#pkg-examples

备注:

这个系列不是一个大而全的package api 指南,只包括作者认为最常见的使用方式,抗议无效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: