在属性lvl中覆盖json.net中的ContractResolver

时间:2015-02-04 13:02:37

标签: json json.net

public class GDALInfoResult
    {
        public GDALInfoResult()
        {
            MetaData = new Dictionary<string, string>();

        }

        public Dictionary<string, string> MetaData { get; set; }


    }
    class Program
    {
        static void Main(string[] args)
        {
            var result = new GDALInfoResult()
            {

            };
            result.MetaData["EXIF_TestSomthing"] = "Hello";

            Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }));

        }
    }

以上代码将打印出来:

{
  "metaData": {
    "exiF_TestSomthing": "Hello"
  }
}

有没有办法可以覆盖MetaData属性,使其不使用Console Write Line中指定的CamelCasePropertyNamesContractResolver

我不希望它更改我的MetaData属性中的名称,但不能更改序列化对象中使用的序列化设置。 (因为我可以在这个演示中,但那只是为了表明我的问题)。

1 个答案:

答案 0 :(得分:0)

以下是诀窍,但接口就像许多额外的代码一样。如果没有其他人提出更好的解决方案,那就行得通。

   public class IgnoreSettingsConverter : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
           return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var settings = new JsonSerializerSettings();
            var s = JsonSerializer.Create(settings);
            s.Serialize(writer, value);
        }
    }
    public class GDALInfoResult
    {
        public GDALInfoResult()
        {
            MetaData = new Dictionary<string, string>();

        }

        [JsonConverter(typeof(IgnoreSettingsConverter))]
        public Dictionary<string, string> MetaData { get; set; }


    }