zoukankan      html  css  js  c++  java
  • go接收json数据处理

    go对json数据进行解码,有两种方式:

    client := &http.Client{}
    request, err := http.NewRequest("GET", "http://dev.babysleep.com/home/admin/user", nil)
    if err != nil {
        log.Fatal(err)
    }
    response, _ := client.Do(request)
    
    // 方式一:json.Unmarshal()
    b, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Println("err=>", err)
    }
    data = []byte(string(b))
    err = json.Unmarshal(data, &user)
    适用场景:如果要处理的JSON数据已经存在内存中,使用json.Unmarshal
    
    // 方式二:json.NewDecoder()
    err := json.NewDecoder(response.Body).Decode(&user)
    适用场景:如果数据来自io.Reader流,或者需要从数据流中解码多个值,使用json.Decoder
             http请求的读取,也属于流的读取
    

    解码的时候 如果要转为结构体类型,需要注意的点是:要保证json的数据字段与要转化的结构体的字段一致,字段类型一致,如果不一致,需要做一些额外的处理。比如:

    // 网站基础导航结构
    type Menu struct {
    	Id        int                 `json:"id,string"`    // json数据中,id为string类型
    	Text      string              `json:"text"`
    	Active    bool                `json:"-"`        // json数据中不显示Active字段
    	Icon      string              `json:"icon"`
    	Href      string              `json:"href"`
    	Css       []string            `json:"css,omitempty"`    //omitempty指定如果值为空,可以忽略该值
    	PluginCss []string            `json:"pluginCss,omitempty"`
            Js        map[string][]string `json:"js,omitempty"`  
    	PluginJs  map[string][]string `json:"pluginJs,omitempty"`
    	Children  []Menu              `json:"children,omitempty"`
    }
    
  • 相关阅读:
    Android的数据存储
    Servlet第一天
    JavaScript高级程序设计读书笔记(3)
    Interesting Papers on Face Recognition
    Researchers Study Ear Biometrics
    IIS 发生意外错误 0x8ffe2740
    Father of fractal geometry, Benoit Mandelbrot has passed away
    Computer vision scientist David Mumford wins National Medal of Science
    Pattern Recognition Review Papers
    盒模型bug的解决方法
  • 原文地址:https://www.cnblogs.com/xinxinmifan/p/go-learning-json.html
Copyright © 2011-2022 走看看