1.6.6 结构体嵌套

  1. 结构体的嵌套经常用于返回或者解析网络请求,如API接口的Response响应

    // Item 基础结构体
    type Item struct {
    	Title string
    	URL   string
    }
    
    // Response 响应结构体
    type Response struct {
    	Data struct {
    		Children []struct {
    			Data Item
    		}
    	}
    }
    
    func main() {
    	jsonStr := `{
    		"data": {
    			"children": [
    				{
    					"data": {
    						"title": "LonelySnow",
    						"url": "http://www.lonelysnow.cn"
    					}
    				}
    			]
    		}
    	}`
    
    	res := Response{}
    	json.Unmarshal([]byte(jsonStr), &res)
    	fmt.Println(res)
    }

    结果:

    {{[{{LonelySnow http://www.lonelysnow.cn}}]}}

Last updated