2

I'm trying unsuccessfully to create a MongoDB GeoJsonFeatureCollection from JSON in ASP.NET core.

(environment: MongoDB C# driver v2.10.2, ASP.NET core v3.1)

// a C# class which contains my geoJson features and intend to store in MongoDB
public class Route
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public GeoJsonFeatureCollection<GeoJson2DCoordinates> Data { get; set; }
}

Then in the ASP.NET core controller, I'd like to have incoming JSON auto-converted to the Route class:

[HttpPost]
public ActionResult<Route> Create(Route route)  // FAILS HERE WITH NO PARAMETERLESS CONSTRUCTOR ERROR!
{
    _routeService.Create(route);  // send it off to MongoDB
    ...
}

I understand that this fails because MongoDB's GeoJsonFeatureCollection doesn't have a parameterless constructor, so the incoming JSON can't be automatically mapped to the C# Route class. But I can't seem to find an obvious workaround to this situation.

Possibilities I've considered:

  1. Skip trying to map to a C# class and just work with BsonDocuments for everything. It seems like querying becomes a bit more complex with this option, and I lose the power of C#. Seems to be advocated here.

  2. Somehow add a custom serializer for GeoJsonFeatureCollection. I have no idea how to do this, but there is a possibly relevant serializer provided in MongoDB:

    https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/GeoJsonObjectModel/Serializers/GeoJsonFeatureCollectionSerializer.cs

  3. Use a string to hold the geoJson Data in my C# class and perform the conversions manually:

    public string Data { get; set; }

    instead of:

    public GeoJsonFeatureCollection<GeoJson2DCoordinates> Data { get; set; }

    and then manually convert the string to a GeoJsonGeometryCollection via:

    var geoCollection = BsonSerializer.Deserialize<GeoJsonGeometryCollection<TCoordinates>>(json);

    but this seems ugly, requiring an extra JSON serialization in my javascript code and manual conversions in every HTTP endpoint.

What to do?

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.