Closed alex3305 closed 3 years ago
After a while of trial and error I figured out how to do deserialization of GeoJSON easily. Example code:
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using NetTopologySuite.Features;
using NetTopologySuite.IO.Converters;
public class GeoJsonSerializer
{
public static JsonSerializerOptions DefaultSerializerOptions
{
get
{
var options = new JsonSerializerOptions {ReadCommentHandling = JsonCommentHandling.Skip};
options.Converters.Add(new GeoJsonConverterFactory());
return options;
}
}
public static void RemoveAllProperties(IFeature feature)
{
// Just replace the AttributesTable with a new one instead of deleting all properties
// because the STJ-serialized Feature has a read-only AttributesTable.
feature.Attributes = new AttributesTable();
}
public static async Task<FeatureCollection> DeserializeGeoJson(string geojson)
{
await using var ms = new MemoryStream(Encoding.UTF8.GetBytes(geojson));
return await Deserialize<FeatureCollection>(ms);
}
private static async Task<T> Deserialize<T>(Stream input)
{
return await JsonSerializer.DeserializeAsync<T>(input, DefaultSerializerOptions);
}
}
Is there any example or documentation on how to convert to and from a
FeatureCollection
with the newSystem.Text.Json
library?