I have a web service trying to return GeoJson data, I keep getting this error
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"The method or operation is not implemented.","ExceptionType":"System.NotImplementedException","StackTrace":" at GeoJSON.Net.Converters.GeometryConverter.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, 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 value)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.WebHost.HttpControllerHandler.d__14.MoveNext()"}}
This is my controller
// 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);
}
This is the method 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;
}
In fiddler I get the error , this is my 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);
}
});
Things I have tried Updgraded newtonsoft to version 6
adding this line to application_start
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
override in the Register method of the WebApi Config:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
So far no good, any ideas anyone ? , thx
here's the fixed class, ensure you use the correct base 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; }
}
}