转自:https://segmentfault.com/q/1010000005025933/a-1020000005032034
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
)
//`json:"*****"` 必须与json串里的字段明对应
type Poi struct{
Srctag string `json:"srctag"`
Poi_id string `json:"poi_id"`
Lng float64 `json:"lng"`
Lat float64 `json:"lat"`
}
func main() {
jsonStr:=`{"srctag":"pgcstation","poi_id":"1110844022022209541","displayname":"test_displayname","address":"test_address","lng":-46.69525,"lat":-23.74456,"coordinate_type":"test_sug_poi_type"}`
//json str 转struct
var poi Poi
if err := json.Unmarshal([]byte(jsonStr), &poi); err == nil {
fmt.Println("================json str 转struct==")
fmt.Println(poi)
fmt.Println(poi.Lng)
fmt.Println(poi.Poi_id)
}
//json str 转map
var res map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &res); err == nil {
fmt.Println("==============json str 转map=======================")
fmt.Println(reflect.TypeOf(res)) //map[string]interface {}
fmt.Println(res)
fmt.Println(res["srctag"])
}
//struct 到json str
if b, err := json.Marshal(poi); err == nil {
fmt.Println("================struct 到json str==")
fmt.Println(string(b))
}
//map 到json str
fmt.Println("================map 到json str=====================")
enc := json.NewEncoder(os.Stdout)
enc.Encode(res)
//array 到 json str
arr := []string{"a", "123", "678", "bxdf"}
array_str, err := json.Marshal(arr)
if err == nil {
fmt.Println("================array 到 json str==")
fmt.Println(string(array_str))
}
//json 到 array []string
var arr1 []string
if err := json.Unmarshal(array_str, &arr1); err == nil {
fmt.Println("================json 到 []string==")
fmt.Println(arr1)
fmt.Println(reflect.TypeOf(arr1[0])) //string
}
}
结果: