I am trying to serialize a FeatureCollection so I can pass it as a request body. To do this I am using a NetTopologySuite.IO.GeoJSON package and using the instruction they provide on their github page. The problem is, when hitting the jsonSerializer.Serialize method, I get an error saying: {"At least one element in the source array could not be cast down to the destination array type."} System.Exception {System.InvalidCastException}.
My method looks like this:
private async Task<IEnumerable<VehicleArea>> GetVehiclesInAreas(FeatureCollection areas)
{
var uri = $"www.someurl/getByArea";
using var httpClient = new HttpClient();
string stringifiedAreas;
var jsonSerializer = GeoJsonSerializer.CreateDefault();
using (var stringWriter = new StringWriter())
using (var jsonwriter = new Newtonsoft.Json.JsonTextWriter(stringWriter))
{
jsonSerializer.Serialize(jsonwriter, areas);
stringifiedAreas = stringWriter.ToString();
}
StringContent content = new StringContent(stringifiedAreas, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(uri, content);
}
The GEOSJON object I am passing in the request body of my controller, that ends up being the areas FeatureCollection provided to the given method looks like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 16,
"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
"coordinates": [
[
[
12.1234,
55.1234
],
[
12.7,
55.7],
[
12.8,
55.8
],
[
12.9,
55.9
],
[
12.1234,
55.1234
]
]
]
}
]
}
},
{
"type": "Feature",
"id": 16,
"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
"coordinates": [
[
[
12.1234,
55.1234
],
[
12.7,
55.7],
[
12.8,
55.8
],
[
12.9,
55.9
],
[
12.1234,
55.1234
]
]
]
}
]
}
}
]
}
Finally, here is a snippet of how the areas object looks like during runtime: