繁体   English   中英

使用App Engine在Golang中解析json以从Google api请求构造

[英]parse json to struct from google api request in golang with App Engine

我实际上正在尝试在golang中使用google map api(在将urlfetch与应用程序引擎结合使用时,当我执行查询时,我无法在结构中获得结果。

我的代码

import (

   "google.golang.org/appengine"
   "google.golang.org/appengine/log"
   "google.golang.org/appengine/urlfetch"
   "net/http"
   "strings"
   "encoding/json"
    "encoding/gob"
    "bytes"
)

func GetCoordinatesByAddress(request *http.Request) bool {

    var results Results

    ctx := appengine.NewContext(request)
    client := urlfetch.Client(ctx)

    resp, err := client.Get("https://maps.googleapis.com/maps/api/geocode/json?address=Suresnes+France"&key=" + ApiKey)
    if err != nil {
      return false
    }

    decoder := json.NewDecoder(resp.Body)
    decoder.Decode(&results)
    log.Debugf(ctx, "", results)
}

type Results struct {
   results []Result
   status string
}

type Result struct {
   address_components []Address
   formatted_address string
   geometry Geometry
   place_id string
   types []string
}

type Address struct {
   long_name string
   short_name string
   Type []string `json:"type"`
}

type Geometry struct {
   bounds Bounds
   location LatLng
   location_type string
   viewport Bounds
}

type Bounds struct {
   northeast LatLng
   southwest LatLng
}

type LatLng struct {
   lat float64
   lng float64
}

查询结果(带有curl)

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Suresnes",
               "short_name" : "Suresnes",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Hauts-de-Seine",
               "short_name" : "Hauts-de-Seine",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Île-de-France",
               "short_name" : "Île-de-France",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "France",
               "short_name" : "FR",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "92150",
               "short_name" : "92150",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "92150 Suresnes, France",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 48.88276,
                  "lng" : 2.2364639
               },
               "southwest" : {
                  "lat" : 48.859284,
                  "lng" : 2.199768
               }
            },
            "location" : {
               "lat" : 48.869798,
               "lng" : 2.219033
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 48.88276,
                  "lng" : 2.2364639
               },
               "southwest" : {
                  "lat" : 48.859284,
                  "lng" : 2.199768
               }
            }
         },
         "place_id" : "ChIJ584OtMVk5kcR4DyLaMOCCwQ",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

查询结果(带有我的go代码)

DEBUG: %!(EXTRA controlgoogle.Results={[] }) 

您能帮我解析此查询结果的结构吗?

谢谢

要解组JSON构造,它需要访问成员,以便可以更新值。 要允许访问,您必须导出struct的成员(通过以大写字母开头成员名称)。 JSON字段也应使用json:"<field_name>"映射到struct的成员。 我已经更新了您的结构。

type Results struct {
   Results []Result `json:"results"`
   Status string `json:"status"`
}

type Result struct {
   AddressComponents []Address `json:"address_components"`
   FormattedAddress string `json:"formatted_address"`
   Geometry Geometry `json:"geometry"`
   PlaceId string `json:"place_id"`
   Types []string `json:"types"`
}

type Address struct {
   LongName string `json:"long_name"`
   ShortName string `json:"short_name"`
   Types []string `json:"types"`
}

type Geometry struct {
   Bounds Bounds `json:"bounds"`
   Location LatLng `json:"location"`
   LocationType string `json:"location_type"`
   Viewport Bounds `json:"viewport"`
}

type Bounds struct {
   Northeast LatLng `json:"northeast"`
   Southwest LatLng `json:"southwest"`
}

type LatLng struct {
   Lat float64 `json:"lat"`
   Lng float64 `json:"lng"`
}

注意结构的字段情况。 如果我没记错的话,marshaller / unmarshaller将忽略小写字段,因此您最终将得到空结构。 尝试将字段命名为大写。

您还可以使用第三方服务(例如Serp API) ,该服务是已经提供JSON解析的Google搜索引擎结果API。

与GoLang集成很容易:

parameter := map[string]string{
    "q":            "Coffee",
    "location":     "Portland"
}

query := newGoogleSearch(parameter)
serpResponse, err := query.json()
results := serpResponse["organic_results"].([]interface{})
first_result := results[0].(map[string]interface{})
fmt.Println(ref["title"].(string))

GitHub: https : //github.com/serpapi/google-search-results-golang

具有json标签的结构字段需要导出(大写字段名称)。 另外,您应该为所有struct字段添加json标记,json标记必须与要解析的json字段相同:

type Address struct {
    LongName  string   `json:"long_name"`
    ShortName string   `json:"short_name"`
    Type      []string `json:"types"`
}
a := `{
    "long_name" : "Suresnes",
    "short_name" : "Suresnes",
    "types" : [ "locality", "political" ]
}`

var addr Address
err := json.NewDecoder(strings.NewReader(a)).Decode(&addr)
if err != nil {
    fmt.Println(err)
}
fmt.Printf("%+v\n", addr)


output: {LongName:Suresnes ShortName:Suresnes Type:[locality political]}

默认情况下,encoding / json包仅封送/解组仅输出字段,因此您应将结构更改为以下形式,以大写开头并具有json:“”标签。

type Results struct {
   Results []Result `json:"results"`
   Status string `json:"status"`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM