Unable to deserialize json property named "$ type"

It seems that the problem is with the json property name with the name "$ type".
If I change the name to "$ typ" or "$ typee", it seems to work.
At first I thought that there is an invisible Unicode character, but it does not seem to be so, since I copy-paste both json and the attribute value in Jon Skeet Unicode Explorer , and I don't see anything strange.

using Newtonsoft.Json;
using System;

namespace ConsoleAppCompare
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{
                                ""$type"": ""someText"",
                                ""$someName"": ""MoreText"",
                                ""$ThisWorksToo"": ""en"",
                                ""Counting"": true
                            }";

            var movie = JsonConvert.DeserializeObject<Movie>(json);

            Console.WriteLine("Type:"+ movie.type); //type is null here
            Console.ReadLine();
        }
    }

    class Movie
    {
        [JsonProperty(PropertyName = "$type")]
        public string type { get; set; }

        [JsonProperty(PropertyName = "$someName")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "$ThisWorksToo")]
        public string Language { get; set; }

        public bool Counting { get; set; }
    }
}

Does anyone have an explanation? I am using Newtonsoft.Json.10.0.3

The update seems to work if I move the property somewhere else

string json = @"{
                 ""$someName"": ""MoreText"",
                 ""$ThisWorksToo"": ""en"",
                  ""$type"": ""someText"",
                  ""Counting"": true
                }";
+4
source share
1 answer

Newtonsoft.Json , . /, JsonSerializerSettings:

new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
}
+3

Source: https://habr.com/ru/post/1690734/


All Articles