Deserialization of DbGeography Entity Framework

0

I have a class Event with a property of the type DbGeography.

public class Event
{
    public long Id { get; set; }
    public DateTime Date { get; set; }
    public DbGeography Location { get; set; }
}

In the class DatabaseHelper I try to load data from a server.

public async Task<IEnumerable<Event>> GetEventsAsync()
{
    var uri = new Uri(string.Format(Constants.EventsUrl, string.Empty));
    var content = await _client.GetStringAsync(uri);
    IEnumerable<Event> events = JsonConvert.DeserializeObject<List<Event>>(content);

    return events;
}

But an error is thrown:

Newtonsoft.Json.JsonSerializationException: Error getting value from 'WellKnownValue' on 'System.Data.Entity.Spatial.DbGeography'.

I did found out that I should use a custom JsonConverter.

// DbGeographyConverter.cs

public class DbGeographyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject location = JObject.Load(reader);
        JToken token = location["Geography"]["WellKnownText"];
        string value = token.ToString();

        System.Data.Entity.Spatial.DbGeography converted = System.Data.Entity.Spatial.DbGeography.PointFromText(value, 4326);
        return converted;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Base serialization is fine 
        serializer.Serialize(writer, value);
    }
}

But when calling http://localhost:57609/api/events, which returns list of Event objects, the following error is thrown:

{"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":"Error while copying content to a stream.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":"   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)","ExceptionType":"System.IO.FileLoadException","StackTrace":"   at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
   at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
   at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
   at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
   at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)
   at System.Reflection.CustomAttribute.IsDefined(RuntimePropertyInfo property, RuntimeType caType)
   at System.Reflection.RuntimePropertyInfo.IsDefined(Type attributeType, Boolean inherit)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers(Type objectType)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteStartArray(JsonWriter writer, Object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)"}}}

What could be the problem?

asp.net
entity-framework
spatial-data
asked on Stack Overflow Jan 4, 2018 by kostik • edited Dec 19, 2019 by Niels R.

1 Answer

1

Problem is you are referencing Newtonsoft.Json 10.0.0.0

Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

It seems version 10.0.0.0 is no longer available on NuGet servers, thus you can't have it locally. No where to download from. Try to update/install existing version. It might work then.

Install-Package Newtonsoft.Json -Version 10.0.3
answered on Stack Overflow Jan 6, 2018 by dropoutcoder

User contributions licensed under CC BY-SA 3.0