json数据转换

晴朗的天空来之不易
2021-3-17 / 0 评论 / 809 阅读 / 正在检测是否收录...

# json

结构体转json ----序列化

# map转json字符串

m :=map[string]string{"type":"10","msg":"hello."}
mjson,_ :=json.Marshal(m)
mString :=string(mjson)
fmt.Printf("print mString:%s",mString)

# 数组对象 转 结构体

//定义一个结构体
type TgisZoomInfo struct {
	Zoom int `json:"zoom"`
	YMin int `json":"yMin"`
	YMax int `json":"yMax"`
	XMin int `json":"xMin"`
	XMax int `json":"xMax"`
}

type TgisDataDB struct {
	lock         sync.Mutex
	FullFilename string
	Cnn          *sql.DB
	Metadata     map[string]string
	ZoomInfos    []TgisZoomInfo // 数组对象存这里
}

func (p *TgisDataDB) parseMetadata() error {
	rows, err := p.Cnn.Query(`SELECT * FROM metadata`)
	if err != nil {
		return err
	}
    //myRows查询的数据结构体 myRows.Datas是数据列表
	myRows := sqlutils.MapMyRows(rows)
	for i := 0; i < int(myRows.RecordCount); i++ {
		row := myRows.Datas[i]
		if row["name"] == "task" || row["name"] == "zoominfo" {
			err := json.Unmarshal([]byte(row["value"].(string)), &p.ZoomInfos)
			if err != nil {
				return err
			}
		} else {
			if p.Metadata == nil {
				p.Metadata = make(map[string]string)
			}
			p.Metadata[row["name"].(string)] = row["value"].(string)
		}
	}
	return nil
}
func (p *TgisDataDB) getgisZoomInfo() error {
	p.lock.Lock()
	defer p.lock.Unlock()
	//ret := make([]gisZoomInfo, 0)
	rows, err := p.Cnn.Query(`SELECT * FROM metadata`)
	if err != nil {
		return err
	}
	myRows := sqlutils.MapMyRows(rows)
	for i := 0; i < int(myRows.RecordCount); i++ {
		// var s gisZoomInfo
		row := myRows.Datas[i]
		if row["name"] == "task" || row["name"] == "zoominfo" {
			//var zoomInfos TZoomInfos
			//strZoominfo := sqlutils.IAS(row["value"])
			strZoominfo := row["value"].(string)

			jsonData := []byte(strZoominfo)
			err := json.Unmarshal(jsonData, &p.ZoomInfos)
			if err == nil {
				fmt.Println(p.ZoomInfos)
				for j := 0; j < len(p.ZoomInfos); j++ {
					var zoomInfo = p.ZoomInfos[j]
					fmt.Println(zoomInfo)
				}
			}
			fmt.Printf("%T\n%v", row["value"], row["value"])
		} else {
			if p.Metadata == nil {
				p.Metadata = make(map[string]string)
			}
			p.Metadata[row["name"].(string)] = row["value"].(string)
		}
		// s.Zoom = int(row["zoomMin"].(int64))
		// s.MinY = int(row["miny"].(int64))
		// s.MaxY = int(row["maxy"].(int64))
		// s.MinX = int(row["minx"].(int64))
		// s.MaxX = int(row["maxx"].(int64))
		// fmt.Println(s)

		// ret = append(ret, s)
	}
	fmt.Println(p.Metadata)
	return nil
}

0