JsonConvert.DeserializeObject (string) returns null value for $id property

Json.Net normally uses $id along with $ref as metadata to preserve object references in JSON. So when it sees $id it assumes that property is not part of the actual JSON property set, but an internal identifier. Thus it does not populate the Id property on your object, even though you included a [JsonProperty] attribute indicating that it should.

UPDATE

As of Json.Net version 6.0.4, there is a new setting by which you can instruct the deserializer to treat these “metadata” properties as normal properties instead of consuming them. All you need to do is set the MetadataPropertyHandling setting to Ignore and then deserialize as usual.

var settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;

var obj = JsonConvert.DeserializeObject<FormDefinitionList>(json, settings);

Prior to version 6.0.4, a workaround was needed to solve this issue. The rest of this answer discusses the possible workarounds. If you are using 6.0.4 or later, you do not need the workaround and can stop reading now.


The simplest workaround I can see is to do a string replace of "$id" with "id" (including the quotes) on the JSON prior to deserializing it, as @Carlos Coelho suggested. Since you would have to do this with each response, if you go this route I would recommend making a simple helper method to avoid code duplication, e.g.:

public static T Deserialize<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json.Replace("\"$id\"", "\"id\""));
}

However, since you said in your comments that you are not so keen on the idea of using a string replace, I looked into other options. I did find one other alternative that might work for you– a custom JsonConverter. The idea behind the converter is that it would try to use Json.Net’s built-in deserialization mechanisms to create and populate the object (sans ID), then manually retrieve the $id property from the JSON and use it to populate the Id property on the object via reflection.

Here is the code for the converter:

public class DollarIdPreservingConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(FormDefinition);
    }

    public override object ReadJson(JsonReader reader, Type objectType,
                           object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        object o = jo.ToObject(objectType);
        JToken id = jo["$id"];
        if (id != null)
        {
            PropertyInfo prop = objectType.GetProperty("Id");
            if (prop != null && prop.CanWrite && 
                prop.PropertyType == typeof(string))
            {
                prop.SetValue(o, id.ToString(), null);
            }
        }
        return o;
    }

    public override void WriteJson(JsonWriter writer, object value, 
                                   JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

I tried to write the converter such that it would work for any object that has the $id — you just need to change the CanConvert method accordingly so that it returns true for all the types that you need to use it for in addition to FormDefinition.

To use the converter, you just need to pass an instance of it to DeserializeObject<T> like this:

FormDefinitionList root = JsonConvert.DeserializeObject<FormDefinitionList>(
                                      json, new DollarIdPreservingConverter());

Important note: you might be tempted to decorate your classes with a JsonConverter attribute instead of passing the converter into the DeserializeObject call, but don’t do this– it will cause the converter to go into a recursive loop until the stack overflows. (There is a way to get the converter to work with the attribute, but you would have to rewrite the ReadJson method to manually create the target object and populate its properties instead of calling jo.ToObject(objectType). It is doable, but a little more messy.)

Let me know if this works for you.

Leave a Comment