WebApi GeoJson错误序列化数据

时间:2014-02-25 13:31:21

标签: c# json serialization asp.net-web-api geojson

我有一个尝试返回GeoJson数据的Web服务,我一直收到此错误

  

{“消息”:“发生错误。”,“ExceptionMessage”:“   'ObjectContent`1'类型无法序列化响应主体   内容类型'application / json;   字符集= UTF-8' “” ExceptionType。 “:” System.InvalidOperationException “ ”堆栈跟踪“:空 ”的InnerException“:{ ”消息“:” 一个   错误已经发生。“,”ExceptionMessage“:”方法或操作是   不   实施 “” ExceptionType。 “:” System.NotImplementedException “ ”堆栈跟踪“:”   在GeoJSON.Net.Converters.GeometryConverter.WriteJson(JsonWriter   writer,Object value,JsonSerializer serializer)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter   writer,JsonConverter转换器,Object值,JsonContract契约,   JsonContainerContract collectionContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter   writer,Object value,JsonContract valueContract,JsonProperty成员,   JsonContainerContract containerContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter   writer,Object value,JsonObjectContract契约,JsonProperty   成员,JsonContainerContract collectionContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter   writer,Object value,JsonContract valueContract,JsonProperty成员,   JsonContainerContract containerContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter   writer,IEnumerable值,JsonArrayContract契约,JsonProperty   成员,JsonContainerContract collectionContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter   writer,Object value,JsonContract valueContract,JsonProperty成员,   JsonContainerContract containerContract,JsonProperty   containerProperty)\ r \ n at   Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter   jsonWriter,Object value,Type objectType)\ r \ n at   Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter   jsonWriter,Object value,Type objectType)\ r \ n at   Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter,Object   价值)\ r \ n at   System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型   type,Object value,Stream writeStream,Encoding   有效编码)\ r \ n at   System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型   type,Object value,Stream writeStream,Encoding   有效编码)\ r \ n at   System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型   type,Object value,Stream writeStream,HttpContent content)\ r \ n at   System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(类型   type,Object value,Stream writeStream,HttpContent内容,   TransportContext transportContext,CancellationToken   cancellationToken)\ r \ n ---从前一个位置开始的堆栈跟踪结束   抛出异常的地方--- \ r \ n at   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务   任务)\ r \ n at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)\ r \ n at   System.Runtime.CompilerServices.TaskAwaiter.GetResult()\ r \ n at   System.Web.Http.WebHost.HttpControllerHandler.d__14.MoveNext()“}}

这是我的控制器

 // POST api/geo
    public List<GeoJSON.Net.Feature.Feature> Post([FromBody] locationsClass loc)
    {

        var lat = loc.lat;
        var lon = loc.lon;
        Geo Geo = new Geo();
        return Geo.GetRndNearybyLocationList(lat, lon, 400); 
    }

这是方法GetRndNearybyLocationList

        public List<GeoJSON.Net.Feature.Feature> GetRndNearybyLocationList(double lat, double lon, int meters)
    {
        LocationObject thisRndLocation = new LocationObject();
        List<LocationObject> locationsList = new List<LocationObject>();

        //List<GeoJSON.Net.Geometry.GeographicPosition> Positions = new List<GeoJSON.Net.Geometry.GeographicPosition>();

        Random rnd = new Random();
        int dice = rnd.Next(1, 7);
        List<GeoJSON.Net.Feature.Feature> featureList = new List<GeoJSON.Net.Feature.Feature>();
        for (int i = 1; i <= dice; i++)
        {
            thisRndLocation = getLocation(lat, lon, meters);

            GeoJSON.Net.Geometry.GeographicPosition latlon = new GeoJSON.Net.Geometry.GeographicPosition(thisRndLocation.lat, thisRndLocation.lon, 0);
            GeoJSON.Net.Geometry.Point point = new GeoJSON.Net.Geometry.Point(latlon);
            Dictionary<string, object> properties = new Dictionary<string, object>();
            properties.Add("Color", "Blue");
            GeoJSON.Net.Feature.Feature feature = new GeoJSON.Net.Feature.Feature(point, properties);
            feature.Id = "FeatureId: " + i;
            featureList.Add(feature);

            //var coOrdinates = new GeoJSON.Net.Geometry.GeographicPosition(thisRndLocation.lat, thisRndLocation.lon);
            //Positions.Add(coOrdinates);
            //locationsList.Add(thisRndLocation);
            //var x = locationsList;

        }
        return featureList;
    }

在fiddler中我得到错误,这是我的Ajax

   $.ajax({
            type: 'Post',
            contentType: "application/json; charset=utf-8",
            url: 'http://localhost:8506/api/' + 'Geo' + '/?alloworigin=true',
            data: JSON.stringify({ lat: lat, lon: lon }),
            dataType: 'json',
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var obj = data[i];
                    console.log(obj.id);
                }
            },
            error: function (msg) {
                alert(msg.responsetext);
            }
        });

我尝试过的事情 将newtonsoft升级到版本6

将此行添加到application_start

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

覆盖WebApi配置的Register方法:

 var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    config.Formatters.Remove(config.Formatters.XmlFormatter);

到目前为止没有任何好处,任何想法? ,thx

这是固定类,确保使用正确的基础GeoJSon

namespace GeoJSON.Net.Geometry
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;



/// <summary>
/// In geography, a point refers to a Position on a map, expressed in latitude and longitude.
/// </summary>
/// <seealso cref="http://geojson.org/geojson-spec.html#point"/>
public class Point : GeoJSONObject, IGeometryObject
{

    /// <summary>
    /// Initializes a new instance of the <see cref="Point"/> class.
    /// </summary>
    /// <param name="coordinates">The Position.</param>
    public Point(GeoJSON.Net.Geometry.GeographicPosition coordinates)
    {
        if (coordinates == null)
        {
            throw new ArgumentNullException("coordinates");
        }

        this.Coordinates = new List<GeoJSON.Net.Geometry.GeographicPosition> { coordinates };
        this.Type = GeoJSONObjectType.Point;
    }


    /// <summary>
    /// Initializes a new instance of the <see cref="Point"/> class.
    /// </summary>
    /// <param name="coordinates">The Position.</param>
    public Point(List<GeoJSON.Net.Geometry.GeographicPosition> coordinates)
    {
        if (coordinates == null)
        {
            throw new ArgumentNullException("coordinates");
        }

        this.Coordinates = coordinates;
        this.Type = GeoJSONObjectType.Point;
    }

    /// <summary>
    /// Gets the Coordinate(s).
    /// </summary>
    /// <value>The Coordinates.</value>
    [JsonProperty(PropertyName = "coordinates", Required = Required.Always)]
    //[JsonConverter(typeof(PositionConverter))]
    public List<GeoJSON.Net.Geometry.GeographicPosition> Coordinates { get; private set; }
}

}

1 个答案:

答案 0 :(得分:1)

在我看来,GeoJSON的库还没有实现write方法。如果我们跳到github的source for that file,那么我们可以看到它实际上还没有实现。然而,该项目的一些分支似乎确实有实施。您可以尝试下载mapbutcher's fork的代码并构建它。