我试图将一个对象反序列化为json,其中位置细节应该转换为geojson格式。试图使用geojson.net nuget包来实现这一点,但是无法获得相同的信息。在net中没有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; }
}我想用Newtonsoft反序列化将请求对象转换为json,但是在请求内部,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]
]
]
}
}
]
}因此,在反序列化Request时,我需要上面的对象来代替值。
发布于 2018-05-31 08:17:41
要确保创建对json对象映射的正确类,请使用visual studio的“粘贴特殊”功能。你能做的就是创建一个新的类,
编辑>粘贴特殊>粘贴JSON类
或者只需访问http://json2csharp.com/并丢弃您的json数据,然后单击Generatebutton...which就会给出您可以简单复制的类。
FYI,VS粘贴特殊生成以下类.
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; }
}两者都可以工作,但给他们一个尝试,看看哪一个给你更容易使用。即使其中一种方法不起作用,您也可以记住这些选项,以供将来参考。
发布于 2020-03-19 12:19:03
请注意,不同的形状类型在几何图形中有不同数量的嵌套数组。例如,我指出需要一个与多多边形不同的容器。您可能需要根据形状类型将:public List<List<List<double>>> coordinates { get; set; }修改为public List<double> coordinates { get; set; }。
发布于 2018-10-06 23:29:10
使用GeoJSON.Net库修改模型如下:
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 FeatureCollection Values { get; set; }
}初始化请求对象:
var polygon = new Polygon(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(20.236237,39.4116761),
new Position(20.2363602,39.4115249),
new Position(20.2365152,39.4110652),
new Position(20.2364942,39.4104468),
new Position(20.236237,39.4116761),
})
});
var featureCollection = new FeatureCollection(new List<Feature>()
{
new Feature(polygon)
});
var request = new Request()
{
Id = 1,
Name = "MyRequest",
Fence = new Fence()
{
Type = 2,
Values = featureCollection
}
};最后序列化对象:
var json = JsonConvert.SerializeObject(request);https://stackoverflow.com/questions/50616994
复制相似问题