go语言的request请求、json解析、marshal、unmarshal

1. 基础假数据

// 20200814182720
// http://gw.xx.com/stock/news?obj=SZ002489&start=1&count=2&type=4&token=xx

{
  "Qid": "",
  "Err": 0,
  "Counter": 1,
  "Data": {
    "Id": 317,
    "RepDataMobileNews": [
      {
        "summary": "浙江永强(002489)证券代码:002489               证券简称:浙江永强           公告编号:2020-045  浙江永强集团股份有限公司  关于回...",
        "id": "3512626",
        "stockcode": "SZ002489",
        "title": "浙江永强:关于回购公司股份的进展公告",
        "otime": "2020-08-03 16:35:05",
        "source": "巨潮资讯网",
        "stockname": "浙江永强",
        "img": "",
        "type": "4",
        "url": "https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/89/002489/gsgg/3512626.json"
      },
      {
        "summary": "浙江永强(002489)证券代码:002489               证券简称:浙江永强            公告编号:2020-044  浙江永强集团股份有限公司  关于...",
        "id": "3492207",
        "stockcode": "SZ002489",
        "title": "浙江永强:关于向关联方购买资产的进展公告",
        "otime": "2020-07-15 17:53:55",
        "source": "巨潮资讯网",
        "stockname": "浙江永强",
        "img": "",
        "type": "4",
        "url": "https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/89/002489/gsgg/3492207.json"
      }
    ]
  }
}

  

2. 基本数据的处理

package main

import (
"encoding/json"
"fmt"
)

func main(){
	
	data, _ := json.Marshal(m)
	fmt.Println(string(data))

	m1 := make(map[string]interface{})
	_ = json.Unmarshal(data, &m1)
	fmt.Println(m1)

}

  

package main

import (
	"encoding/json"
	"fmt"
)

func main() {

	//json字符中的"引号,需用\进行转义,否则编译出错
	jsonStr := []byte("{\"name\":\"张三\",\"age\":18,\"high\":true,\"sex\":\"男\",\"class\":{\"name\":\"1班\",\"level\":3}}")

	//1.Unmarshal的第一个参数是json字符串,第二个参数是接受json解析的数据结构。 第二个参数必须是指针,否则无法接收解析的数据
	var jsonResults map[string]interface{}
	err := json.Unmarshal(jsonStr, &jsonResults)

	//解析失败会报错,如json字符串格式不对,缺"号,缺}等。
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(jsonResults)
	//map[age:18 class:map[level:3 name:1班] high:true name:张三 sex:男]

}
// unmarshal的用法

  

3.  请求接口返回json使用unmarshal解析

package main

import (
	"encoding/json"
	"fmt"
	"github.com/asmcos/requests"
	"reflect"
)

// // 20200814182720
//// http://gw.xx.com/stock/news?obj=SZ002489&start=1&count=2&type=4&token=xx
//
//{
//  "Qid": "",
//  "Err": 0,
//  "Counter": 1,
//  "Data": {
//    "Id": 317,
//    "RepDataMobileNews": [
//      {
//        "summary": "浙江永强(002489)证券代码:002489               证券简称:浙江永强           公告编号:2020-045  浙江永强集团股份有限公司  关于回...",
//        "id": "3512626",
//        "stockcode": "SZ002489",
//        "title": "浙江永强:关于回购公司股份的进展公告",
//        "otime": "2020-08-03 16:35:05",
//        "source": "巨潮资讯网",
//        "stockname": "浙江永强",
//        "img": "",
//        "type": "4",
//        "url": "https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/89/002489/gsgg/3512626.json"
//      },
//      {
//        "summary": "浙江永强(002489)证券代码:002489               证券简称:浙江永强            公告编号:2020-044  浙江永强集团股份有限公司  关于...",
//        "id": "3492207",
//        "stockcode": "SZ002489",
//        "title": "浙江永强:关于向关联方购买资产的进展公告",
//        "otime": "2020-07-15 17:53:55",
//        "source": "巨潮资讯网",
//        "stockname": "浙江永强",
//        "img": "",
//        "type": "4",
//        "url": "https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/89/002489/gsgg/3492207.json"
//      }
//    ]
//  }
//}

// go requests and db to mongo

func main() {

	code := "SZ002740"
	newsUrl := fmt.Sprintf("http://gw.xx.com/stock/news?obj=%s&start=1&count=2&type=4&token=xxx", code)

	fmt.Println(newsUrl)

	req := requests.Requests()
	req.Header.Set("Content-Type", "application/json")
	resp, err := req.Get(newsUrl)
	fmt.Println(resp, err)

	// Go的文档中说到,nil是预定义的标识符,代表指针、通道、函数、接口、映射或切片的零值,也就是预定义好的一个变量:
	// 指针表示指向内存的地址,如果对为nil的指针进行解引用的话就会导致panic。
	if err == nil {

		// interface{}类型其实是个空接口,即没有方法的接口。go的每一种类型都实现了该接口。
		//因此,任何其他类型的数据都可以赋值给interface{}类型。
		var jsonResults map[string]interface{}
		//1.Unmarshal的第一个参数是json字符串,第二个参数是接受json解析的数据结构。 第二个参数必须是指针,否则无法接收解析的数据
		err := json.Unmarshal([]byte(resp.Content()), &jsonResults)
		if err != nil {
			fmt.Println(err)
		}

		for k, v := range jsonResults {

			fmt.Println("------------------------")
			fmt.Println(reflect.TypeOf(k), reflect.TypeOf(v), k, v)

			isMap := reflect.ValueOf(v).Kind() == reflect.Map
			fmt.Println(isMap)

			//强制转换为什么类型?
			//cant range over v , type interface {}

			if k == "Data" && isMap {
				fmt.Println("++++++++++++++++++++++++++")
				for key, value := range v.(map[string]interface{}) {
					fmt.Println(key, value)

				}

			}
		}

	}
}

//------------------------
//string float64 Err 0
//false
//------------------------
//string float64 Counter 1
//false
//------------------------
//string map[string]interface {} Data map[Id:317 RepDataMobileNews:[map[id:3524899 img: otime:2020-08-12 17:41:31 source:巨潮资讯网 stockcode:SZ002740 stockname:爱迪尔 summary:爱迪尔
//(002740)股票代码:002740             股票简称:爱迪尔          公告编号:2020-105 号  福建省爱迪尔珠宝实业股份有限公司  关于... title:爱迪尔:关于公司股票交易异常波动的公告 typ
//e:4 url:https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/40/002740/gsgg/3524899.json] map[id:3521943 img: otime:2020-08-10 19:26:30 source:巨潮资讯网 stockcode:SZ002740 stockname:爱
//迪尔 summary:爱迪尔(002740)股票代码:002740             股票简称:爱迪尔          公告编号:2020-104 号  福建省爱迪尔珠宝实业股份有限公司  关于... title:爱迪尔:关于再次延期回
//复深圳证券交易所2019年年报问询函的公告 type:4 url:https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/40/002740/gsgg/3521943.json]]]
//true
//++++++++++++++++++++++++++
//Id 317
//RepDataMobileNews [map[id:3524899 img: otime:2020-08-12 17:41:31 source:巨潮资讯网 stockcode:SZ002740 stockname:爱迪尔 summary:爱迪尔(002740)股票代码:002740             股票简称:
//爱迪尔          公告编号:2020-105 号  福建省爱迪尔珠宝实业股份有限公司  关于... title:爱迪尔:关于公司股票交易异常波动的公告 type:4 url:https://mnews.gw.com.cn/wap/data/ipad/s
//tock/SZ/40/002740/gsgg/3524899.json] map[id:3521943 img: otime:2020-08-10 19:26:30 source:巨潮资讯网 stockcode:SZ002740 stockname:爱迪尔 summary:爱迪尔(002740)股票代码:002740
//股票简称:爱迪尔          公告编号:2020-104 号  福建省爱迪尔珠宝实业股份有限公司  关于... title:爱迪尔:关于再次延期回复深圳证券交易所2019年年报问询函的公告 type:4 url
//:https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/40/002740/gsgg/3521943.json]]
//------------------------
//string string Qid
//false

  

 

4. 使用github-request模块

package main

import (
	"fmt"
	"github.com/asmcos/requests"
)

// go requests and db to mongo
func main() {

	code := "SZ002740"
	newsUrl := fmt.Sprintf("http://gw.xx.com/stock/news?obj=%s&start=1&count=2&type=4&token=xxx", code)

	fmt.Println(newsUrl)

	req := requests.Requests()
	req.Header.Set("Content-Type", "application/json")
	resp, err := req.Get(newsUrl)
	fmt.Println(resp, err)

	// Go的文档中说到,nil是预定义的标识符,代表指针、通道、函数、接口、映射或切片的零值,也就是预定义好的一个变量:
	// 指针表示指向内存的地址,如果对为nil的指针进行解引用的话就会导致panic。
	if err == nil {

		// interface{}类型其实是个空接口,即没有方法的接口。go的每一种类型都实现了该接口。
		//因此,任何其他类型的数据都可以赋值给interface{}类型。

		var jsonResults map[string]interface{}
		resp.Json(&jsonResults)

		for k, v := range jsonResults {

			fmt.Println("------------------------")
			fmt.Println(k, v)

		}
	}

}

// ------------------------
//Counter 1
//------------------------
//Data map[Id:317 RepDataMobileNews:[map[id:3524899 img: otime:2020-08-12 17:41:31 source:巨潮资讯网 stockcode:SZ002740 stockname:爱迪尔 summary:爱迪尔(002740)股票代码:002740
//      股票简称:爱迪尔          公告编号:2020-105 号  福建省爱迪尔珠宝实业股份有限公司  关于... title:爱迪尔:关于公司股票交易异常波动的公告 type:4 url:https://mnews.gw.com.cn
///wap/data/ipad/stock/SZ/40/002740/gsgg/3524899.json] map[id:3521943 img: otime:2020-08-10 19:26:30 source:巨潮资讯网 stockcode:SZ002740 stockname:爱迪尔 summary:爱迪尔(002740)股票
//代码:002740             股票简称:爱迪尔          公告编号:2020-104 号  福建省爱迪尔珠宝实业股份有限公司  关于... title:爱迪尔:关于再次延期回复深圳证券交易所2019年年报问询函
//的公告 type:4 url:https://mnews.gw.com.cn/wap/data/ipad/stock/SZ/40/002740/gsgg/3521943.json]]]
//------------------------
//Qid
//------------------------
//Err 0

  

 

posted @ 2020-08-14 18:51  Adamanter  阅读(1264)  评论(0)    收藏  举报