2013-03-30 17 views
6

我想将geojson字符串解组为合适的结构类型。 我有,我想解组为同一结构三个不同的GeoJSON的字符串:用于geojson解组的合适结构类型

var jsonBlobPointString = []byte(`{"Type":"Point", "Coordinates":[1.1,2.0]}`) 
var jsonBlobLineString = []byte(`{"Type":"LineString", "Coordinates":[[1.1,2.0],[3.0,6.3]]}`) 
var jsonBlobPolygonString = []byte(`{"Type":"Polygon", "Coordinates":[[[1.1,2.0],[3.0,6.3],[5.1,7.0],[1.1,2.0]]]}`) 

我想出了一个结构类型是我可不是完全满意:

type GeojsonType struct { 
    Type string 
    Coordinates interface{} 
} 

请参阅此链接完整示例: http://play.golang.org/p/Bt-51BX__A

我宁愿不使用接口{}作坐标。 我会反而使用somehting给我一些验证例如坐标[] float64的点 和坐标[] [] float64的LineString。

是否可以创建一个结构类型,以便Point,LineString和Polygon都可以在坐标中表示而不使用接口?

+0

您是否尝试过实现Unmarshaler接口? – Mikke

回答

6

你想要的是从相同的json字典中创建3种不同类型的对象。

据我知道这是不可能的,但是你可以使用RawMessage型延迟JSON解码和使用位前处理like this

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type Point struct { 
    Coordinates []float64 
} 

type Line struct { 
    Points [][]float64 
} 

type Polygon struct { 
    Lines [][][]float64 
} 

type GeojsonType struct { 
    Type  string 
    Coordinates json.RawMessage 
    Point  Point 
    Line  Line 
    Polygon  Polygon 
} 

var jsonBlob = []byte(`[ 
{"Type":"Point", "Coordinates":[1.1,2.0]}, 
{"Type":"LineString", "Coordinates":[[1.1,2.0],[3.0,6.3]]}, 
{"Type":"Polygon", "Coordinates":[[[1.1,2.0],[3.0,6.3],[5.1,7.0],[1.1,2.0]]]} 
]`) 

func main() { 
    var geojsonPoints []GeojsonType 
    err := json.Unmarshal(jsonBlob, &geojsonPoints) 
    if err != nil { 
     fmt.Println("error:", err) 
    } 

    // Postprocess the coordinates 

    for i := range geojsonPoints { 
     t := &geojsonPoints[i] 

     switch t.Type { 
     case "Point": 
      err = json.Unmarshal(t.Coordinates, &t.Point.Coordinates) 
     case "LineString": 
      err = json.Unmarshal(t.Coordinates, &t.Line.Points) 
     case "Polygon": 
      err = json.Unmarshal(t.Coordinates, &t.Polygon.Lines) 
     default: 
      panic("Unknown type") 
     } 
     if err != nil { 
      fmt.Printf("Failed to convert %s: %s", t.Type, err) 
     } 
     fmt.Printf("%+v\n", t) 
    } 
} 

它打印

&{Type:Point Coordinates:[91 49 46 49 44 50 46 48 93] Point:{Coordinates:[1.1 2]} Line:{Points:[]} Polygon:{Lines:[]}} 
&{Type:LineString Coordinates:[91 91 49 46 49 44 50 46 48 93 44 91 51 46 48 44 54 46 51 93 93] Point:{Coordinates:[]} Line:{Points:[[1.1 2] [3 6.3]]} Polygon:{Lines:[]}} 
&{Type:Polygon Coordinates:[91 91 91 49 46 49 44 50 46 48 93 44 91 51 46 48 44 54 46 51 93 44 91 53 46 49 44 55 46 48 93 44 91 49 46 49 44 50 46 48 93 93 93] Point:{Coordinates:[]} Line:{Points:[]} Polygon:{Lines:[[[1.1 2] [3 6.3] [5.1 7] [1.1 2]]]}} 
+0

非常感谢!我认为这正是我需要的。 – Gunnis