美文网首页
2019-05-10

2019-05-10

作者: sujeking | 来源:发表于2019-05-10 09:56 被阅读0次

对象

struct

type Studen struct {
    Name string 
    age int
}
  • 需要注意的是 对象的属性如果是小写 那么就是私有的 只有本包才可以访问 序列化以及转json是无效的 首字母大写是公开的,可以转json和序列化

JSON

Obj —> string

encoding/json

type Studen struct {
    Name string `json:"name"` //对应json的字段
    age int
}

func test(){
    jsons,err := json.Marshal(stu)
    if err != nil {
        //转json字符串错误
    }
    var json_str = string(jsons)
}

string —> Obj

type Studen struct {
    Name interface{} `json:"name"`
    age interface{}
}

//json字符中的"引号,需用\进行转义,否则编译出错
    //json字符串沿用上面的结果,但对key进行了大小的修改,并添加了sex数据
    data:="{\"name\":\"张三\",\"Age\":18,\"high\":true,\"sex\":\"男\",\"CLASS\":{\"naME\":\"1班\",\"GradE\":3}}"
    str:=[]byte(data)

    //1.Unmarshal的第一个参数是json字符串,第二个参数是接受json解析的数据结构。
    //第二个参数必须是指针,否则无法接收解析的数据,如stu仍为空对象StuRead{}
    //2.可以直接stu:=new(StuRead),此时的stu自身就是指针
    stu:=StuRead{}
    err:=json.Unmarshal(str,&stu)

    //解析失败会报错,如json字符串格式不对,缺"号,缺}等。
    if err!=nil{
        fmt.Println(err)
    }
    fmt.Println(stu)

相关文章

网友评论

      本文标题:2019-05-10

      本文链接:https://www.haomeiwen.com/subject/xljooqtx.html