1. 程式人生 > >golang struct 定義中json``解析說明

golang struct 定義中json``解析說明

在程式碼學習過程中,發現struct定義中可以包含`json:"name"`的宣告,所以在網上找了一些資料研究了一下

package main

import (
    "encoding/json"
    "fmt"
)

//在處理json格式字串的時候,經常會看到宣告struct結構的時候,屬性的右側還有小米點括起來的內容。`TAB鍵左上角的按鍵,~線同一個鍵盤`

type Student struct {
    StudentId      string `json:"sid"`
    StudentName    string `json:"sname"`
    StudentClass   
string `json:"class"` StudentTeacher string `json:"teacher"` } type StudentNoJson struct { StudentId string StudentName string StudentClass string StudentTeacher string } //可以選擇的控制欄位有三種: // -:不要解析這個欄位 // omitempty:當欄位為空(預設值)時,不要解析這個欄位。比如 false、0、nil、長度為 0 的 array,map,slice,string
// FieldName:當解析 json 的時候,使用這個名字 type StudentWithOption struct { StudentId string //預設使用原定義中的值 StudentName string `json:"sname"` // 解析(encode/decode) 的時候,使用 `sname`,而不是 `Field` StudentClass string `json:"class,omitempty"` // 解析的時候使用 `class`,如果struct 中這個值為空,就忽略它 StudentTeacher string
`json:"-"` // 解析的時候忽略該欄位。預設情況下會解析這個欄位,因為它是大寫字母開頭的 } func main() { //NO.1 with json struct tag s := &Student{StudentId: "1", StudentName: "fengxm", StudentClass: "0903", StudentTeacher: "feng"} jsonString, _ := json.Marshal(s) fmt.Println(string(jsonString)) //{"sid":"1","sname":"fengxm","class":"0903","teacher":"feng"} newStudent := new(Student) json.Unmarshal(jsonString, newStudent) fmt.Println(newStudent) //&{1 fengxm 0903 feng} //Unmarshal 是怎麼找到結構體中對應的值呢?比如給定一個 JSON key Filed,它是這樣查詢的: // 首先查詢 tag 名字(關於 JSON tag 的解釋參看下一節)為 Field 的欄位 // 然後查詢名字為 Field 的欄位 // 最後再找名字為 FiElD 等大小寫不敏感的匹配欄位。 // 如果都沒有找到,就直接忽略這個 key,也不會報錯。這對於要從眾多資料中只選擇部分來使用非常方便。 //NO.2 without json struct tag so := &StudentNoJson{StudentId: "1", StudentName: "fengxm", StudentClass: "0903", StudentTeacher: "feng"} jsonStringO, _ := json.Marshal(so) fmt.Println(string(jsonStringO)) //{"StudentId":"1","StudentName":"fengxm","StudentClass":"0903","StudentTeacher":"feng"} //NO.3 StudentWithOption studentWO := new(StudentWithOption) js, _ := json.Marshal(studentWO) fmt.Println(string(js)) //{"StudentId":"","sname":""} studentWO2 := &StudentWithOption{StudentId: "1", StudentName: "fengxm", StudentClass: "0903", StudentTeacher: "feng"} js2, _ := json.Marshal(studentWO2) fmt.Println(string(js2)) //{"StudentId":"1","sname":"fengxm","class":"0903"} }

 

 

參考:

GO語言JSON簡介