我有一个包含 NetTopologySuite 多边形的简单模型:
public class MyModel
{
[Newtonsoft.Json.JsonConverter(typeof(MyPolygonConverter))]
public NetTopologySuite.Geometries.Polygon poly { get; set; }
}
我已经使用 NetTopologySuite.IO.GeoJson 构建了一个自定义转换器:
public class MyPolygonConverter : JsonConverter<Polygon>
{
public override void WriteJson(JsonWriter writer, Polygon value, JsonSerializer serializer)
{
var geoJsonSerializer = NetTopologySuite.IO.GeoJsonSerializer.Create();
using var stringWriter = new StringWriter();
using var jsonWriter = new JsonTextWriter(stringWriter);
geoJsonSerializer.Serialize(jsonWriter, value);
var geoJson = stringWriter.ToString();
writer.WriteValue(geoJson);
}
...
}
然后我创建一个模型对象并将其序列化:
var model = new MyModel
{
poly = new Polygon(new LinearRing(new[]
{
new Coordinate(-100, 45),
new Coordinate(-98, 45),
new Coordinate(-99, 46),
new Coordinate(-100, 45),
}))
};
var geoJson = JsonConvert.SerializeObject(model, Formatting.None,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
});
我得到的包含 Polygon 作为转义的 GeoJson 字符串:
{
"poly" : "{\"type\":\"Polygon\",\"coordinates\":[[[-100.0,45.0],[-98.0,45.0],[-99.0,46.0],[-100.0,45.0]]]}"
}
我想要的是多边形作为json,在json对象中:
{
"poly" : {
"type" : "Polygon",
"coordinates" : [
[
[-100.0,45.0],
[-98.0,45.0],
[-99.0,46.0],
[-100.0,45.0]
]
]
}
}
我在想的是我根本不应该使用 JsonConverter ,而是别的东西。
但是什么?