2 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
您應(yīng)該使用與輸入文檔匹配的結(jié)構(gòu)來(lái)解組:
type Entry struct {
Lat string `json:"lat"`
Lon string `json:"lon"`
DisplayName string `json:"display_name"`
Address struct {
Address string `json:"address"`
Country string `json:"country"`
Code string `json:"country_code"`
} `json:"address"`
Geo struct {
Type string `json:"type"`
Coordinates [][][]float64 `json:"coordinates"`
} `json:"geojson"`
}
然后解組為一個(gè)條目數(shù)組:
var entries []Entry
json.Unmarshal(data,&entries)
并且,用于entries構(gòu)造Locations

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
您需要對(duì) Unmarshal 的結(jié)構(gòu)更加精確。根據(jù)官方 JSON 規(guī)范,您還需要在密鑰周圍加上雙引號(hào)。省略引號(hào)僅適用于 JavaScript,JSON 需要這些。
最后一件事,我知道這很愚蠢,但是最后一個(gè)內(nèi)部數(shù)組之后的最后一個(gè)逗號(hào)也是無(wú)效的,必須刪除它:
package main
import (
"encoding/json"
"fmt"
)
type Location struct {
Lat string `json:"lat"`
Lng string `json:"lon"`
DisplayName string `json:"display_name"`
Address Address `json:"address"`
GeoJSON Geo `json:"geojson"`
}
type Address struct {
Address string `json:"address"`
Country string `json:"country"`
CountryCode string `json:"country_code"`
}
type Geo struct {
Type string `json:"type"`
Coordinates [][]Coordinate `json:"coordinates"`
}
type Coordinate [2]float64
func main() {
inputJSON := `
[
{
"lat": "41.189301799999996",
"lon": "11.918255998031015",
"display_name": "Some place",
"address": {
"address": "123 Main St.",
"country": "USA",
"country_code": "+1"
},
"geojson": {
"type": "Polygon",
"coordinates": [
[
[14.4899021,41.4867039],
[14.5899021,41.5867039]
]
]
}
}
]`
var locations []Location
if err := json.Unmarshal([]byte(inputJSON), &locations); err != nil {
panic(err)
}
fmt.Printf("%#v\n", locations)
}
- 2 回答
- 0 關(guān)注
- 295 瀏覽
添加回答
舉報(bào)