[golang] struct转JSON,解析JSON

//定义一个结构体
   type header struct {
		Encryption  string `json:"encryption"`
		Timestamp   int64  `json:"timestamp"`
		Key         string `json:"key"`
		Partnercode int    `json:"partnercode"`
	}

//转换成JSON字符串
   headerO1 := header{
		Encryption:  "sha",
		Timestamp:   1482463793,
		Key:         "2342874840784a81d4d9e335aaf76260",
		Partnercode: 10025,
	}
	jsons, errs := json.Marshal(headerO1) //转换成JSON返回的是byte[]
	if errs != nil {
	  fmt.Println(errs.Error())
	}
	fmt.Println(string(jsons)) //byte[]转换成string 输出
  //输出:{"encryption":"sha","timestamp":1482463793,"key":"2342874840784a81d4d9e335aaf76260","partnercode":10025}
  
  //解析JSON成结构体(1)
  var headers string = `{"encryption":"md5","timestamp":1482463793,"key":"2342874840784a81d4d9e335aaf76260","partnercode":100034}`
  headerObj := header{}
  json.Unmarshal([]byte(headers), &headerObj)//json解析到结构体里面
  fmt.Println(headerObj) //输入结构体
  //输出 {sha 1482463793 2342874840784a81d4d9e335aaf76260 10025}
  
  
  //解析JSON成结构体(2)指定解析的长度
  
    headerReader := io.LimitReader(strings.NewReader(headers), 1024)
	headerObj3 := header{}
	errs := json.NewDecoder(headerReader).Decode(&headerObj3)
	if errs != nil {
		fmt.Println(errs.Error())
	}
  
  
empty

你可能感兴趣的:(go,lang,golang)