2 回答

TA貢獻1824條經驗 獲得超5個贊
您應該使用與輸入文檔匹配的結構來解組:
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"`
}
然后解組為一個條目數組:
var entries []Entry
json.Unmarshal(data,&entries)
并且,用于entries構造Locations

TA貢獻1886條經驗 獲得超2個贊
您需要對 Unmarshal 的結構更加精確。根據官方 JSON 規范,您還需要在密鑰周圍加上雙引號。省略引號僅適用于 JavaScript,JSON 需要這些。
最后一件事,我知道這很愚蠢,但是最后一個內部數組之后的最后一個逗號也是無效的,必須刪除它:
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 關注
- 290 瀏覽
添加回答
舉報