【问题标题】:C# MongoDB GeoJsonPoint JSON ObjectC# MongoDB GeoJsonPoint JSON 对象
【发布时间】:2020-07-03 12:36:52
【问题描述】:

我遇到了如何在我的 ASP.NET Core 3 应用程序中使用 mongodb.driver 构造我的地理定位对象的问题

我的对象

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; }
}

我只是在做一个直接的插入并传递对象。如果我遗漏了它插入的位置,请查找。

这是我试图在一个简单的帖子中传递给 api 的 JSON 对象。

{
"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
    ]
}

}

我得到的错误。

System.NotSupportedException:不支持没有无参数构造函数的引用类型的反序列化。键入 'MongoDB.Driver.GeoJsonObjectModel.GeoJsonPoint`1[MongoDB.Driver.GeoJsonObjectModel.GeoJson2DGeographicCoordinates]'

【问题讨论】:

  • 看起来“位置”在 JSON 字符串中的构造不正确。您可以通过序列化以下结果来检查格式是否正确:var location = new GeoJsonPoint&lt;GeoJson2DGeographicCoordinates&gt;(new GeoJson2DGeographicCoordinates(32.0, 91.0)); :: 这将向您展示预期的内容。
  • Nkosi 您提出的示例是最简单的方法。谢谢你。它在 json 中想要的对象很大且令人费解,无法正确处理。私有集很容易实现。

标签: c# json mongodb asp.net-core geolocation


【解决方案1】:

Nksoi 帮助解答

人物对象

 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));
    }
}

控制器

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

        return Ok();
    }

JSON 对象

 "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

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2011-09-09
    • 1970-01-01
    • 2023-02-16
    • 2013-07-23
    相关资源
    最近更新 更多