I have a data table containing information related to cities along with the boundaries stored as a polygon. I wrote the following function to convert the data into a JSON file.
public static string DataTableToGeoJSONString(DataTable dataTable)
{
var cityData = new
{
type = "FeatureCollection",
features = dataTable.AsEnumerable().Select(record => new {
type = "Feature",
id = Convert.ToString(record["Id"]),
properties = new
{
name = Convert.ToString(record["Name"]),
density = Convert.ToInt32(record["NumCri"])
},
geometry = new
{
type = "Polygon",
coordinates = new [] {
(record["Coordinates"])
}
},
})
};
return JsonConvert.SerializeObject(cityData);
}
I understand that the polygon is an array of arrays hence the following code statement does not work
type = "Polygon",
coordinates = new [] {
(record["Coordinates"])
Any advice on how to store the array of arrays into coordinates variable? Please note that the record["Coordinates"] stores the coordinate information in the following format:
[[[23.444,44.444],[24.444,45.222],...]]]
CodePudding user response:
Take a look at this example. It does the following:
- Parse the literal as an array
- Get the first item from the array and cast the item from a generic token to an array
- Loop over every item in the array from step 2
- Cast the currently iterated item from a generic token to an array
- Create a new PointF and add it to a collection based on the values of the currently iterated array from step 4
Private Function ParseCoordinates(json As String) As IEnumerable(Of PointF)
Dim outerArray As JArray = JArray.Parse(json)
Dim innerArray As JArray = DirectCast(outerArray.Item(0), JArray)
Dim points As New List(Of PointF)()
For Each item As JToken In innerArray
Dim itemArray As JArray = DirectCast(item, JArray)
points.Add(New PointF(itemArray.Item(0).Value(Of Single)(), itemArray.Item(1).Value(Of Single)()))
Next
Return points
End Function
Fiddle: https://dotnetfiddle.net/mAJgfz
Keep in mind that this assumes that your data is perfect. I would highly recommend you take the time to setup some conditional statements to make sure that:
- The outerArray variable can be parsed to a JArray
- There are more than 0 items in outerArray before declaring innerArray
- The innerArray variable can be cast to a JArray
- The itemArray variable can be cast to a JArray
- There is more than 1 item in the itemArray variable before setting them as the X/Y values of the PointF
- The values of itemArray can be cast to a Single