golang json to structure

First we look at this json string

{
    "resp": {
        "respCode": "000000",
        "respMsg": "成功",
        "app": {
            "appId": "xxxxxx"
        }
    }
}

go built json string parsing package "encoding / json"

Then we need to define the structure of the body.

According to analysis json library, in fact, each brace is a structure

Then dismantling the structure as follows:

// innermost structure represented 
type appInfo struct { 
    Appid String `JSON: " for appId " ` 
} 

// the representative structure of the second layer 
type Response struct { 
    RespCode String   `JSON: " respCode " ` 
    RespMsg   String   `JSON: " respMsg " ` 
    the appInfo appInfo JSON`: " App " ` 
} 

type a JsonResult struct { 
    Resp` JSON Response: " RESP "`    // represents the outermost layer of the structure of curly braces 
}

 

Naming structure must follow the first letter capitalized , otherwise it will ignore the json library members,

While the back json: " XXXXXX is required in the name string and json consistent: as the outermost layer  json:"**resp**" and in the json string { " RESP " consistent

Then follows the actual code analysis

package main
import (
    "fmt"
        "encoding/json"
)
type appInfo struct {
    Appid string `json:"appId"`
}
type response struct {
    RespCode string  `json:"respCode"`
    RespMsg  string  `json:"respMsg"`
    AppInfo  appInfo `json:"app"`
}
type JsonResult struct {
    Resp response `json:"resp"`
}
func main() {
    jsonstr := `{"resp": {"respCode": "000000","respMsg": "成功","app": {"appId": "xxxxxx"}}}`
    var JsonRes JsonResult 
        json.Unmarshal(body, &JsonRes)
        fmt.Println("after parse", JsonRes)
}

 

Guess you like

Origin www.cnblogs.com/feiquan/p/11468792.html