JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 1746
耶瑟儿~
耶瑟儿~ 2020-11-22 03:22

I have a class that contains an enum property, and upon serializing the object using JavaScriptSerializer, my json result contains the integer valu

27条回答
  •  被撕碎了的回忆
    2020-11-22 04:09

    Not sure if this is still relevant but I had to write straight to a json file and I came up with the following piecing several stackoverflow answers together

    public class LowercaseJsonSerializer
    {
        private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            ContractResolver = new LowercaseContractResolver()
        };
    
        public static void Serialize(TextWriter file, object o)
        {
            JsonSerializer serializer = new JsonSerializer()
            {
                ContractResolver = new LowercaseContractResolver(),
                Formatting = Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore
            };
            serializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
            serializer.Serialize(file, o);
        }
    
        public class LowercaseContractResolver : DefaultContractResolver
        {
            protected override string ResolvePropertyName(string propertyName)
            {
                return Char.ToLowerInvariant(propertyName[0]) + propertyName.Substring(1);
            }
        }
    }
    

    It assures all my json keys are lowercase starting according to json "rules". Formats it cleanly indented and ignores nulls in the output. Aslo by adding a StringEnumConverter it prints enums with their string value.

    Personally I find this the cleanest I could come up with, without having to dirty the model with annotations.

    usage:

        internal void SaveJson(string fileName)
        {
            // serialize JSON directly to a file
            using (StreamWriter file = File.CreateText(@fileName))
            {
                LowercaseJsonSerializer.Serialize(file, jsonobject);
            }
        }
    

提交回复
热议问题