【问题标题】:Deserializing geoJSON in a Web API 2 controller in c#在 c# 中的 Web API 2 控制器中反序列化 geoJSON
【发布时间】:2015-06-29 12:11:22
【问题描述】:

我需要传递一些包含 geoJSON 对象的 JSON 并将其反序列化到此模型:

public class GeoTag
    {
        public Guid ID { get; set; }
        public DbGeography Geography { get; set; }
        public string Tag { get; set; }
        public Guid UserID { get; set; }
    }

我在 .NET 4.5 中使用 Web API 2 控制器,如下所示:

[ResponseType(typeof(GeoTag))]
        public async Task<IHttpActionResult> PostQuestion(GeoTag geoTag)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //Do some stuff

            return CreatedAtRoute("DefaultApi", new { id = geoTag.ID }, geoTag);
        }

这是我的 JSON:

{
"Tag": "food",
"Geography": {
"coordinates": ["-0.1337","51.50998"],
"type": "Point"
}

}

我无法让控制器方法解释Geography;它正在返回此消息:

Unable to find a constructor to use for type System.Data.Spatial.DbGeography. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Geography.coordinates', line 4, position 19.

有谁知道我正在做的事情是否可行,或者我的方法是否错误?

【问题讨论】:

  • 您提供的 Json 示例不是有效的 Json。
  • 先改你的Json,无效。
  • 像下面的答案一样改变你的 Json。
  • 感谢@KiShOrE。我已经按照您在下面的答案中描述的那样更改了 JSON,但仍然无法正常工作。我已经更新了这个问题并包含了从我的网络方法返回的消息。
  • DbGeography 不是 GeoJSON。

标签: c# .net-4.5 asp.net-web-api2 geojson


【解决方案1】:

像这样改变你的 Json,

{ "Tag": "food", "Geography": { "coordinates": ["-0.1337","51.50998"], "type": "Point" } }

它会起作用的.. :)

【讨论】:

  • 感谢@KiShOrE。我已经更改了 JSON,但没有任何乐趣。我已经用你的 JSON 更新了这个问题,并包含了从我的 web 方法返回的消息。有什么想法吗?
  • 我添加了返回到上述问题的消息:开始'无法找到用于类型 System.Data.Spatial.DbGeography 的构造函数'
猜你喜欢
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
相关资源
最近更新 更多