c# - 如何在 C# 中序列化和反序列化 geojson

标签 c# geojson geojson.net

我正在尝试将对象反序列化为 json,其中位置详细信息应转换为 geojson 格式。试图使用 geojson.net nuget 包实现这一点,但我无法实现相同的目标。网络中没有适用于 geojson 的示例。
我的请求对象:

public class Request
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Fence Fence { get; set; }
}
public class Fence
{
    public int Type { get; set; }
    public List<PValues> Values { get; set; }
}

public class PValues
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

我想将请求对象转换为 json,我可以使用 Newtonsoft 反序列化来实现,但在请求 PValues 内部必须转换为 geojson 多边形类型我如何在 c# 中做到这一点?

我是 GeoJson 的新手,但是当我阅读规范时,多边形规范如下所示
    {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [80.227249, 12.901617],
            [80.227764, 12.888553],
            [80.232056, 12.89006],
            [80.233086, 12.900779],
            [80.227249, 12.901617]
          ]
        ]
      }
    }
  ]
}

所以当我反序列化请求类时,我需要上面的对象来代替值。

最佳答案

为确保您创建正确的类来映射 json 对象,请使用 Visual Studio 的“特殊粘贴”功能。你可以用它做的是,创建一个新类,

Edit > Paste Special > Paste JSON as classes



或者简单地访问 http://json2csharp.com/ 并将您的 json 数据放入并单击生成按钮......然后它将为您提供可以简单复制的类。

仅供引用,VS Paste 特别生成以下类...
    class YourClassName
    {

        public class Rootobject
        {
            public string type { get; set; }
            public Feature[] features { get; set; }
        }

        public class Feature
        {
            public string type { get; set; }
            public Properties properties { get; set; }
            public Geometry geometry { get; set; }
        }

        public class Properties
        {
        }

        public class Geometry
        {
            public string type { get; set; }
            public float[][][] coordinates { get; set; }
        }

    }

http://json2csharp.com/ 将生成以下类...
public class Properties
{
}

public class Geometry
{
    public string type { get; set; }
    public List<List<List<double>>> coordinates { get; set; }
}

public class Feature
{
    public string type { get; set; }
    public Properties properties { get; set; }
    public Geometry geometry { get; set; }
}

public class RootObject
{
    public string type { get; set; }
    public List<Feature> features { get; set; }
}

两者都可以工作,但请试一试,看看哪个更易于使用。即使其中之一不起作用,您也可以记住这些选项以备将来引用。

关于c# - 如何在 C# 中序列化和反序列化 geojson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50616994/

相关文章:

javascript - 如何将 JSON 转换为 GeoJSON

OpenLayers:如何设置 GeoJson 属性的样式

c# - Solidworks API C#/VB.net 设置 Enum 属性

c# - Windows Phone 8 SD 卡文件的文件列表

c# - .Net 二进制反序列化

c# - 使用 .NET 2.0 在 XP 上运行 .NET 4.5 程序

onclicklistener - 在 Google Maps Android API 中通过 onclick 选择功能