无法反序列化名为“$ type”的

时间:2017-12-13 19:53:38

标签: c# json.net

json属性名称“$ type”似乎存在问题 如果我将名称更改为“$ typ”或“$ typee”,它似乎正在工作 起初我以为有一个不可见的Unicode字符,但这似乎并非如此,因为我将json和属性值复制粘贴到Jon Skeet's Unicode Explorer并且我看不到任何奇怪的

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; }
    }
}

有没有人有解释? 我正在使用Newtonsoft.Json.10.0.3

更新 如果我移动其他地方的其他地方似乎有效

string json = @"{
                 ""$someName"": ""MoreText"",
                 ""$ThisWorksToo"": ""en"",
                  ""$type"": ""someText"",
                  ""Counting"": true
                }";

2 个答案:

答案 0 :(得分:4)

它是Newtonsoft.Json中的保留名称,用于表示类的Type的序列化。通过指定JsonSerializerSettings:

启用序列化/反序列化
new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
}

答案 1 :(得分:0)

您应该使用JsonSerializerSettings。 用打击代码反序列化您的json字符串:

JsonSerializerSettings settings = new JsonSerializerSettings
{
      MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
      DateParseHandling = DateParseHandling.None
};

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