8

我想从我的种子文件中为我的用户对象播种“位置”数据

C# 对象,其中 Point 是 aNetTopologySuite.Geometries.Point是我的用户对象的一部分

  public class User: IdentityUser<int> {
      // member data here
      public Point Location { get; set; } // has lat/lng data points
  }

我通过做这样的事情在启动时将数据播种到我的数据库

public void SeedUsers()
{
    if (!_userManager.Users.Any())
    {
        var userData = System.IO.File.ReadAllText("Data/UserSeedData.json");
        var users = JsonConvert.DeserializeObject<List<User>>(userData);

        var roles = new List<Role>
        {
            new Role{Name = "Member"},
            new Role{Name = "Admin"},
            new Role{Name = "Moderator"},
            new Role{Name = "VIP"},
        };

        foreach (var role in roles)
        {
            _roleManager.CreateAsync(role).Wait();
        }

        foreach (var user in users)
        {
            user.Photos.SingleOrDefault().IsApproved = true;
            _userManager.CreateAsync(user, "password").Wait();
            _userManager.AddToRoleAsync(user, "Member").Wait();
        }
     }
 }

使用这样的 json 数组的 json 文件“UserSeedData.json”,我希望能够在其中粘贴某种代表 lng/lat 数据点的“位置”数据。

{
  "Email": "myemailaddress@gmail.com",
  "Username": "Lola",
  "Gender": "female",
  "DateOfBirth": "1994-02-21",
  "Password": "password",
  "Created": "2017-08-02",
  "LastActive": "2017-08-02",
  "Introduction": "blah blah blah",
  "LookingFor": "blah blah blah",
  "City": "San Francisco",
  "Country": "United States",
  "Longitude": -122.431297,
  "Latitude": 37.773972,
  "Location": // something here!!!
  "Photos": [{
    "url": "https://randomuser.me/api/portraits/women/3.jpg",
    "isMain": true,
    "description": "Non deserunt labore sunt ex laboris et adipisicing ullamco officia minim."
  }]
}

现在我知道在我的种子方法中我可以做这样的事情,但我正在寻找一种方法将它包含在我的 .json 文件中,这样我就可以使用不同的数据点

foreach (var user in users)
{
    user.Photos.SingleOrDefault().IsApproved = true;
    user.Location = new Point(-122.4194155, 37.7749295) { SRID = 4326 };
    _userManager.CreateAsync(user, "password").Wait();
    _userManager.AddToRoleAsync(user, "Member").Wait();
}
4

4 回答 4

12

NetTopologySuite有一个单独的 nuget NetTopologySuite.IO.GeoJSON,用于使用 Json.NET 将 NetTopologySuite 类型从 JSON 序列化到 JSON 序列。它包括几何对象的转换器,例如Point. 如果您将此 nuget 添加到您的项目中,您将能够将几何实体添加Point到您的数据模型中并直接(反)序列化模型。

为此,首先将NetTopologySuite.IO.GeoJSON添加到您的项目中。

然后添加以下扩展方法:

public static partial class JsonExtensions
{
    public static T LoadFromFileWithGeoJson<T>(string path, JsonSerializerSettings settings = null)
    {
        var serializer = NetTopologySuite.IO.GeoJsonSerializer.CreateDefault(settings);
        serializer.CheckAdditionalContent = true;
        using (var textReader = new StreamReader(path))
        using (var jsonReader = new JsonTextReader(textReader))
        {
            return serializer.Deserialize<T>(jsonReader);
        }
    }
}

并在您的问题中为您的模型添加一个Location属性:User

public class User : IdentityUser<int>
{
    public Point Location { get; set; }

    // Remainder unchanged.
    // ...
}

现在,a 的 JSON 格式Point如下所示:

{"type":"Point","coordinates":[-122.431297,37.773972]}

因此,将您的 JSON 文件编辑为如下所示:

[
  {
    "Location": {
      "type": "Point",
      "coordinates": [
        -122.431297,
        37.773972
      ]
    },
    // Remainder unchanged

完成所有这些后,您将能够非常简单地反序列化您的 JSON 文件,如下所示:

var users = JsonExtensions.LoadFromFileWithGeoJson<List<User>>("Data/UserSeedData.json");

笔记:

演示小提琴在这里

于 2019-07-26T22:39:18.460 回答
3

您可以子类化NetTopologySuite.Geometries.Point并添加一个[JsonConstructor]来解析您的 json 文件。它应该是对其余代码的直接替换。

public class MyPoint : Point
{
    [JsonConstructor]
    public MyPoint(double latitude, double longitude, int srid)
        :base(new GeoAPI.Geometries.Coordinate(longitude, latitude))
    {
        SRID = srid;
    }
}

请注意,纬度 = y 和经度 = x,所以顺序是相反的。

在你MyPoint的班级交换PointUser

public class User: IdentityUser<int> {
  // member data here
  public MyPoint Location { get; set; }
}

它应该按原样与您的 json 一起使用。

于 2019-07-29T14:10:21.233 回答
1

由于 NetTopogiySuite 的 Point 对象不包含无参数构造函数,因此您无法在脱轨期间轻松映射 JSON。

但是,您可以轻松创建自己的 Location 对象,然后将值映射到循环内的 NetTopologySuite 的 Point 对象。

首先,定义一个新的 Location 对象...

public class Location
{
    public double Longitude { get; set; }
    public double Latitude { get; set; }
    public int SRID { get; set; }
}

接下来,使用以下行更新 JSON 的位置行以定义 Location 对象:

"Location": {"Longitude":-122.4194155, "Latitude":37.7749295, "SRID":4326},

完整的 JSON:

[{
        "Email": "myemailaddress@gmail.com",
        "Username": "Lola",
        "Gender": "female",
        "DateOfBirth": "1994-02-21",
        "Password": "password",
        "Created": "2017-08-02",
        "LastActive": "2017-08-02",
        "Introduction": "blah blah blah",
        "LookingFor": "blah blah blah",
        "City": "San Francisco",
        "Country": "United States",
        "Longitude": -122.431297,
        "Latitude": 37.773972,
        "Location": {"Longitude":-122.4194155, "Latitude":37.7749295, "SRID":4326},
        "Photos": [{
            "url": "https://randomuser.me/api/portraits/women/3.jpg",
            "isMain": true,
            "description": "Non deserunt labore sunt ex laboris et adipisicing ullamco officia minim."
        }]
    }]

接下来,更新您的 User 对象以使用您的新 Location 对象并在 NetTopologySuite 的 Point 对象上设置 JsonIgnore 属性:

public class User : IdentityUser<int>
{
    // member data here

    public Location Location { get; set; }

    [JsonIgnore]
    public Point LocationPoint { get; set; } // has lat/lng data points
}

最后,更新您的 foreach 循环以映射数据...

foreach (var user in users)
{
    user.Photos.SingleOrDefault().IsApproved = true;
    user.LocationPoint = new Point(user.Location.Longitude, user.Location.Latitude) {SRID = user.Location.SRID};
    _userManager.CreateAsync(user, "password").Wait();
    _userManager.AddToRoleAsync(user, "Member").Wait();
}

总而言之,您可能需要重新考虑直接在您的 User 对象中使用 NetTopologySuite 的 Point 对象,而是使用您自己的 Location 对象。然后,您将转置到更接近实际使用 Point 的代码的 NetTopologySuite 的 Point 对象。不过,这实际上取决于您的应用程序。

于 2019-07-26T17:48:37.137 回答
0

聚会有点晚了,但这是我对此的看法:您可以轻松地使其Point与当前的 Json Serializer 设置兼容。

[DataContract]
public class GeoLocation : NetTopologySuite.Geometries.Point
{
    const int GoogleMapSRID = 4326 ;

    public GeoLocation(double latitude, double longitude)
        : base(x: longitude, y: latitude) =>
          base.SRID = GoogleMapsSRID;

    [DataMember]
    public double Longitude => base.X;

    [DataMember]
    public double Latitude => base.Y;
}

DataContract和是这里的DataMember关键:

new GeoLocation(42.9074, -78.7911).ToJson() => {"longitude":42.9074,"latitude":-78.7911}
于 2020-03-09T04:21:56.587 回答