JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 2117
耶瑟儿~
耶瑟儿~ 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:06

    This is easily done by adding a ScriptIgnore attribute to the Gender property, causing it to not be serialised, and adding a GenderString property which does get serialised:

    class Person
    {
        int Age { get; set; }
    
        [ScriptIgnore]
        Gender Gender { get; set; }
    
        string GenderString { get { return Gender.ToString(); } }
    }
    
    0 讨论(0)
  • 2020-11-22 04:08

    You can actually use a JavaScriptConverter to accomplish this with the built-in JavaScriptSerializer. By converting your enum to a Uri you can encode it as a string.

    I've described how to do this for dates but it can be used for enums as well. Custom DateTime JSON Format for .NET JavaScriptSerializer.

    0 讨论(0)
  • 2020-11-22 04:09

    In .net core 3 this is now possible with the built-in classes in System.Text.Json (edit: System.Text.Json is also available as a NuGet package for .net core 2.0 and .net framework 4.7.2 and later versions according to the docs):

    var person = new Person();
    // Create and add a converter which will use the string representation instead of the numeric value.
    var stringEnumConverter = new System.Text.Json.Serialization.JsonStringEnumConverter();
    JsonSerializerOptions opts = new JsonSerializerOptions();
    opts.Converters.Add(stringEnumConverter);
    // Generate json string.
    var json = JsonSerializer.Serialize<Person>(person, opts);
    

    To configure JsonStringEnumConverter with attribute decoration for the specific property:

    using System.Text.Json.Serialization;
    
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public Gender Gender { get; set; }
    

    If you want to always convert the enum as string, put the attribute at the enum itself.

    [JsonConverter(typeof(JsonStringEnumConverter))] 
    enum Gender { Male, Female }
    
    0 讨论(0)
  • 2020-11-22 04:09

    This is an old question but I thought I'd contribute just in case. In my projects I use separate models for any Json requests. A model would typically have same name as domain object with "Json" prefix. Models are mapped using AutoMapper. By having the json model declare a string property that is an enum on domain class, AutoMapper will resolve to it's string presentation.

    In case you are wondering, I need separate models for Json serialized classes because inbuilt serializer comes up with circular references otherwise.

    Hope this helps someone.

    0 讨论(0)
  • 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);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 04:09
    new JavaScriptSerializer().Serialize(  
        (from p   
        in (new List<Person>() {  
            new Person()  
            {  
                Age = 35,  
                Gender = Gender.Male  
            }  
        })  
        select new { Age =p.Age, Gender=p.Gender.ToString() }  
        ).ToArray()[0]  
    );
    
    0 讨论(0)
提交回复
热议问题