在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ GO/ Go JSON實例
Go panic錯誤處理實例
Go命令行參數(shù)實例
Go可變參數(shù)的函數(shù)實例
Go通道同步實例
Go非阻塞通道操作實例
Go指針實例
Go數(shù)字解析實例
Go語言指針
Go超時(timeouts)實例
Go速率限制實例
Go信號實例
Go Base64編碼實例
Go計時器實例
Go命令行標志實例
Go原子計數(shù)器實例
Go語言切片
Go隨機數(shù)實例
Go語言類型轉(zhuǎn)換
Go排序?qū)嵗?/span>
Go時間格式化/解析實例
Go URL解析實例
Go字符串函數(shù)實例
Go語言常量
Go for循環(huán)語句實例
Go函數(shù)多個返回值實例
Go切片實例
Go行過濾器實例
Go語言接口
Go語言數(shù)組
Go語言變量
Go字符串格式化實例
Go斷續(xù)器實例
Go if/else語句實例
Go通道緩沖實例
Go錯誤實例
Go語言映射
Go執(zhí)行過程實例
Go函數(shù)實例
Go有狀態(tài)的goroutines實例
Go按自定義函數(shù)排序?qū)嵗?/span>
Go語言作用域規(guī)則
Go時代(Epoch)實例
Go變量實例
Go互斥體實例
Go語言范圍(range)
Go程序?qū)嵗?/span>
Go語言入門
Go通道路線實例
Go閉包(匿名函數(shù))實例
Go Select實例
Go通道范圍實例
Go集合函數(shù)實例
Hello World程序?qū)嵗?/span>
Go環(huán)境變量實例
Go語言運算符
Go讀取文件實例
Go延遲(defer)實例
Go SHA1哈希實例
Go語言條件和決策
Go語言錯誤處理
Go通道實例
Go指針實例
Go時間日期實例
Go語言字符串
Go語言循環(huán)
Go語言基礎(chǔ)語法
Go語言開發(fā)環(huán)境安裝配置
Go常量實例
Go語言結(jié)構(gòu)體
Go寫文件實例
Go正則表達式實例
Go JSON實例
Go語言教程
Go關(guān)閉通道實例
Go接口實例
Go語言遞歸
Go switch語句實例
Go函數(shù)遞歸實例
Go退出程序?qū)嵗?/span>
Go語言程序結(jié)構(gòu)
Go范圍實例
Go語言函數(shù)
Go工作池實例
Go語言數(shù)據(jù)類型

Go JSON實例

Go提供對JSON編碼和解碼的內(nèi)置支持,包括內(nèi)置和自定義數(shù)據(jù)類型。
我們將使用兩個結(jié)構(gòu)來演示下面的自定義類型的編碼和解碼。

首先,我們將看到基本數(shù)據(jù)類型到JSON字符串的編碼。 這里有一些原子值的例子。

具體的每個函數(shù),可參考示例中的代碼 -

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.com/go/go_environment.html

json.go的完整代碼如下所示 -

package main

import "encoding/json"
import "fmt"
import "os"

// We'll use these two structs to demonstrate encoding and
// decoding of custom types below.
type Response1 struct {
    Page   int
    Fruits []string
}
type Response2 struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}

func main() {

    // First we'll look at encoding basic data types to
    // JSON strings. Here are some examples for atomic
    // values.
    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))

    strB, _ := json.Marshal("gopher")
    fmt.Println(string(strB))

    // And here are some for slices and maps, which encode
    // to JSON arrays and objects as you'd expect.
    slcD := []string{"apple", "peach", "pear"}
    slcB, _ := json.Marshal(slcD)
    fmt.Println(string(slcB))

    mapD := map[string]int{"apple": 5, "lettuce": 7}
    mapB, _ := json.Marshal(mapD)
    fmt.Println(string(mapB))

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

    // You can use tags on struct field declarations
    // to customize the encoded JSON key names. Check the
    // definition of `Response2` above to see an example
    // of such tags.
    res2D := &Response2{
        Page:   1,
        Fruits: []string{"apple", "peach", "pear"}}
    res2B, _ := json.Marshal(res2D)
    fmt.Println(string(res2B))

    // Now let's look at decoding JSON data into Go
    // values. Here's an example for a generic data
    // structure.
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

    // We need to provide a variable where the JSON
    // package can put the decoded data. This
    // `map[string]interface{}` will hold a map of strings
    // to arbitrary data types.
    var dat map[string]interface{}

    // Here's the actual decoding, and a check for
    // associated errors.
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

    // In order to use the values in the decoded map,
    // we'll need to cast them to their appropriate type.
    // For example here we cast the value in `num` to
    // the expected `float64` type.
    num := dat["num"].(float64)
    fmt.Println(num)

    // Accessing nested data requires a series of
    // casts.
    strs := dat["strs"].([]interface{})
    str1 := strs[0].(string)
    fmt.Println(str1)

    // We can also decode JSON into custom data types.
    // This has the advantages of adding additional
    // type-safety to our programs and eliminating the
    // need for type assertions when accessing the decoded
    // data.
    str := `{"page": 1, "fruits": ["apple", "peach"]}`
    res := Response2{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res)
    fmt.Println(res.Fruits[0])

    // In the examples above we always used bytes and
    // strings as intermediates between the data and
    // JSON representation on standard out. We can also
    // stream JSON encodings directly to `os.Writer`s like
    // `os.Stdout` or even HTTP response bodies.
    enc := json.NewEncoder(os.Stdout)
    d := map[string]int{"apple": 5, "lettuce": 7}
    enc.Encode(d)
}

執(zhí)行上面代碼,將得到以下輸出結(jié)果 -

F:\worksp\golang>go run json.go
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"Page":1,"Fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
map[num:6.13 strs:[a b]]
6.13
a
{1 [apple peach]}
apple
{"apple":5,"lettuce":7}

上一篇:Go Select實例下一篇:Go語言接口