zoukankan      html  css  js  c++  java
  • json _ golang

    Go offer built-in support for JSON encoding and decoding, including to and from built-in and custom data types

    package main
    
    import (
        "encoding/json"
        "fmt"
        "os"
    )
    
    type Response1 struct {
        Page   int
        Fruits []string
    }
    
    type Response2 struct {
        Page   int      `json:"page"`
        Fruits []string `json:"fruits"`
    }
    
    func main() {
    
        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))
    
        slcD := []string{"apple", "peach", "pear"}
        slcB, _ := json.Marshal(slcD)
        fmt.Println(string(slcB))
    
        mapD := map[string]int{"apple": 5, "letture": 7}
        mapB, _ := json.Marshal(mapD)
        fmt.Println(string(mapB))
    
        res1D := &Response1{
            Page:   1,
            Fruits: []string{"apple", "peach", "pear"}}
        res1B, _ := json.Marshal(res1D)
        fmt.Println(string(res1B))
    
        res2D := &Response2{
            Page:   1,
            Fruits: []string{"apple", "peach", "pear"}}
        res2B, _ := json.Marshal(res2D)
        fmt.Println(string(res2B))
    
        byt := []byte(`{"num":6.13,"strs":["a", "b"]}`)
    
        var dat map[string]interface{}
    
        if err := json.Unmarshal(byt, &dat); err != nil {
            panic(err)
        }
    
        fmt.Println(dat)
    
        num := dat["num"].(float64)
        fmt.Println(num)
    
        strs := dat["strs"].([]interface{})
        str1 := strs[0].(string)
        fmt.Println(str1)
    
        str := `{"page": 1, "fruits": ["apple", "peach"]}`
        res := &Response2{}
        json.Unmarshal([]byte(str), &res)
        fmt.Println(res)
        fmt.Println(res.Fruits[0])
        enc := json.NewEncoder(os.Stdout)
        d := map[string]int{"apple": 5, "lettuce": 7}
        enc.Encode(d)
    }
    true
    1
    2.34
    "gopher"
    ["apple","peach","pear"]
    {"apple":5,"letture":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}
  • 相关阅读:
    oracle中rownum和rowid的区别和用法
    jsp中,对window对象的简单总结
    下拉列表框实现二级联动
    window.showModalDialog()的简单用法
    javascript中的正则表达式
    java实现树型结构样式
    几个数据库的驱动、连接
    Java桌面程序中设置一个软件的系统托盘
    【动态规划】求两字符串连续最大公共子串长度
    大整数相乘
  • 原文地址:https://www.cnblogs.com/jackkiexu/p/4365548.html
Copyright © 2011-2022 走看看