codecutout / JsonApiSerializer

JsonApiSerializer supports configurationless serializing and deserializing objects into the json:api format (http://jsonapi.org).
MIT License
113 stars 46 forks source link

Please Emphasize Requirement of "Id" Property Naming for Deserialization #129

Open GuyPaddock opened 3 years ago

GuyPaddock commented 3 years ago

I know the current "read me" file states that any object with an "Id" field is considered a resource object, but other docs also mention that fields can be aliased with JsonObject annotations. As a result, it's easy for someone to assume (incorrectly) that if you have a property aliased to id, that property will be used by the JsonConverter, when in fact the converter does not use aliases for searching.

For example, this will not work:

using System;
using Newtonsoft.Json;

namespace MyModels
{
    public class MyModel
    {
        [JsonProperty("id")]
        public string MyModelId { get; set; }
    }
}

You will know that you have an improperly-named Id field if you are getting this error:

"Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'jsonapi', line 1, position 11.'"

It would be great if this was noted in the Read Me.