C# MongoDB GeoJsonPoint JSON Object

Viewed 757

I am having an issue of how to structure my geolocation object in my ASP.NET Core 3 application using the mongodb.driver

My object

public class Person
{
    [BsonId]
    public ObjectId Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string PhoneNumber { get; set; }
    public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set; }
}

I am just doing a straight insertone and passing the object. If I leave out the location it inserts find.

Here is the JSON object I am trying to pass to the api in a simple post.

{
"firstName": "Paul",
"lastName": "Staley",
"email": "someemail@nowhere.com",
"address": "12345 E 1st Ave",
"state": "AA",
"zipCode": "11111",
"phoneNumber": "555-555-5555",
"location":  {

    "coordinates": [
        0.123321,
        0.3453455
    ]
}

}

The error I get.

System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'MongoDB.Driver.GeoJsonObjectModel.GeoJsonPoint`1[MongoDB.Driver.GeoJsonObjectModel.GeoJson2DGeographicCoordinates]'

1 Answers

Answer helped by Nksoi

Person Object

 public class Person
 {
    [BsonId]
    public ObjectId Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string PhoneNumber { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location
    { get; private set; }
    public void SetLocation(double lon, double lat) => SetPosition(lon, lat);


    private void SetPosition(double lon, double lat)
    {
        Latitude = lat;
        Longitude = lon;
        Location = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(
            new GeoJson2DGeographicCoordinates(lon, lat));
    }
}

Controller

 [HttpPost]
    public IActionResult CreatePerson(Person person)
    {
        person.SetLocation(person.Longitude, person.Latitude);
        _personRepository.CreatePerson(person);

        return Ok();
    }

JSON Object

 "firstName": "Paul",
 "lastName": "Staley",
 "email": "someemail@nowhere.com",
 "address": "12345 E 1st Ave",
 "state": "AA",
 "zipCode": "11111",
 "phoneNumber": "555-555-5555",
 "latitude": 32.0,
 "longitude": 91.0
Related