开发者

Unmarshal JSON from HTTP response to GeoJSON geometry

I use Go and Resty to make a GET Request, which returns the data as JSON like this:

[{"id":12548,"geom":"{\"type\": \"LineString\", \"coordinates\": [[14.2455, 53.5468], [14.6548, 53.5765]]}"}]

I want to unmarshal it in the following struct:

type river struct {
    id   integer                `json:"id"`
    Geometry geojson.Geometry   `json:"geom"`
}

using

if err := json.Unmarshal([]byte(response), &river); err != nil {
    panic(err)
}

I get the following error: Error: json: cannot unmarshal string into Go struct field river.Geometry of type geojson.Geometry

The Geometry is of this type

type Geometry struct {
    Type        string           `json:"type"`
    BBox        *json.RawMessage `json:"bbox,omitempty"`
    CRS         *CRS             `json:"crs,omitempty"`
    Coordinates *json.RawMessage `json:"coordinates,omitempty"`
    Geometries  *json.RawMessage `json:"geometries,omitempty"`
}

I don't know how to get my response into a GeoJSON geometry object.开发者_开发百科

I already tried to use response.Body() and response.String() instead of response

if err := json.Unmarshal([]byte(response.Body()), &river); err != nil {
    panic(err)
}

but without success.


for your first question, as Go compiler said, you can't unmarshal to struct directly, you should make a variable of that struct, then unmarshal that string to this variable. for example:

type river struct {
    id   integer                `json:"id"`
    Geometry geojson.Geometry   `json:"geom"`
}

r := river{}
if err := json.Unmarshal([]byte(response), &r); err != nil {
    panic(err)
}

and I didn't get your second question, I think the answer to the first question should work for the second one as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜