Selectively use default JSON converter









up vote
5
down vote

favorite












I use the following in my Web API project's Startup.cs to JSON-serialize Enums into strings:



// Configure JSON Serialization
var jsonSerializationSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSerializationSettings.Formatting = Newtonsoft.Json.Formatting.None;
jsonSerializationSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());


This is to avoid decorating every Enum property with [JsonConverter(typeof(StringEnumConverter))]



Now, how can I selectively opt out of my global serialization setting for some Enum properties and use the default serializer that converts to integers?










share|improve this question























  • Ideally you shall only decorate the required properties instead of the Global setting
    – Mrinal Kamboj
    Sep 28 '16 at 5:30










  • Do you want to opt out for specific properties, or for specific enums?
    – dbc
    Sep 28 '16 at 5:49










  • @dcb For specific properties, probably by using an attribute.
    – orad
    Sep 28 '16 at 5:55














up vote
5
down vote

favorite












I use the following in my Web API project's Startup.cs to JSON-serialize Enums into strings:



// Configure JSON Serialization
var jsonSerializationSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSerializationSettings.Formatting = Newtonsoft.Json.Formatting.None;
jsonSerializationSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());


This is to avoid decorating every Enum property with [JsonConverter(typeof(StringEnumConverter))]



Now, how can I selectively opt out of my global serialization setting for some Enum properties and use the default serializer that converts to integers?










share|improve this question























  • Ideally you shall only decorate the required properties instead of the Global setting
    – Mrinal Kamboj
    Sep 28 '16 at 5:30










  • Do you want to opt out for specific properties, or for specific enums?
    – dbc
    Sep 28 '16 at 5:49










  • @dcb For specific properties, probably by using an attribute.
    – orad
    Sep 28 '16 at 5:55












up vote
5
down vote

favorite









up vote
5
down vote

favorite











I use the following in my Web API project's Startup.cs to JSON-serialize Enums into strings:



// Configure JSON Serialization
var jsonSerializationSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSerializationSettings.Formatting = Newtonsoft.Json.Formatting.None;
jsonSerializationSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());


This is to avoid decorating every Enum property with [JsonConverter(typeof(StringEnumConverter))]



Now, how can I selectively opt out of my global serialization setting for some Enum properties and use the default serializer that converts to integers?










share|improve this question















I use the following in my Web API project's Startup.cs to JSON-serialize Enums into strings:



// Configure JSON Serialization
var jsonSerializationSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSerializationSettings.Formatting = Newtonsoft.Json.Formatting.None;
jsonSerializationSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());


This is to avoid decorating every Enum property with [JsonConverter(typeof(StringEnumConverter))]



Now, how can I selectively opt out of my global serialization setting for some Enum properties and use the default serializer that converts to integers?







c# asp.net asp.net-web-api json.net






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 28 '16 at 6:07









dbc

52.3k765116




52.3k765116










asked Sep 28 '16 at 5:28









orad

5,534134982




5,534134982











  • Ideally you shall only decorate the required properties instead of the Global setting
    – Mrinal Kamboj
    Sep 28 '16 at 5:30










  • Do you want to opt out for specific properties, or for specific enums?
    – dbc
    Sep 28 '16 at 5:49










  • @dcb For specific properties, probably by using an attribute.
    – orad
    Sep 28 '16 at 5:55
















  • Ideally you shall only decorate the required properties instead of the Global setting
    – Mrinal Kamboj
    Sep 28 '16 at 5:30










  • Do you want to opt out for specific properties, or for specific enums?
    – dbc
    Sep 28 '16 at 5:49










  • @dcb For specific properties, probably by using an attribute.
    – orad
    Sep 28 '16 at 5:55















Ideally you shall only decorate the required properties instead of the Global setting
– Mrinal Kamboj
Sep 28 '16 at 5:30




Ideally you shall only decorate the required properties instead of the Global setting
– Mrinal Kamboj
Sep 28 '16 at 5:30












Do you want to opt out for specific properties, or for specific enums?
– dbc
Sep 28 '16 at 5:49




Do you want to opt out for specific properties, or for specific enums?
– dbc
Sep 28 '16 at 5:49












@dcb For specific properties, probably by using an attribute.
– orad
Sep 28 '16 at 5:55




@dcb For specific properties, probably by using an attribute.
– orad
Sep 28 '16 at 5:55












1 Answer
1






active

oldest

votes

















up vote
3
down vote



accepted










You could add a dummy converter to the properties in question that does nothing:



public class NoConverter : JsonConverter

public override bool CanConvert(Type objectType)

// Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
throw new NotImplementedException();


public override bool CanRead get return false;

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

throw new NotImplementedException();


public override bool CanWrite get return false;

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

throw new NotImplementedException();




Then attach it to the property using [JsonConverter(typeof(NoConverter))]. Having done so, the JsonConverter attribute's converter supersedes the globally specified converter, but since CanRead and CanWrite both return false no conversion is performed. For collections of enums, you could use [JsonProperty(ItemConverterType = typeof(NoConverter))].



For instance, if you define the types:



public enum Foo A, B, C 

public class RootObject

[JsonConverter(typeof(NoConverter))]
public Foo FooAsInteger get; set;

public Foo FooAsString get; set;



Then



var root = new RootObject FooAsInteger = Foo.B, FooAsString = Foo.B ;

var json = JsonConvert.SerializeObject(root, Formatting.Indented, new StringEnumConverter());

Console.WriteLine(json);


Produces the output




"FooAsInteger": 1,
"FooAsString": "B"



Note that you can also apply NoConverter directly to the enum, if you want all occurrences of the enum in all data models to be serialized as an integer:



[JsonConverter(typeof(NoConverter))]
public enum FooAlwaysAsInteger A, B, C


Sample fiddle.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39738714%2fselectively-use-default-json-converter%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote



    accepted










    You could add a dummy converter to the properties in question that does nothing:



    public class NoConverter : JsonConverter

    public override bool CanConvert(Type objectType)

    // Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
    throw new NotImplementedException();


    public override bool CanRead get return false;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

    throw new NotImplementedException();


    public override bool CanWrite get return false;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

    throw new NotImplementedException();




    Then attach it to the property using [JsonConverter(typeof(NoConverter))]. Having done so, the JsonConverter attribute's converter supersedes the globally specified converter, but since CanRead and CanWrite both return false no conversion is performed. For collections of enums, you could use [JsonProperty(ItemConverterType = typeof(NoConverter))].



    For instance, if you define the types:



    public enum Foo A, B, C 

    public class RootObject

    [JsonConverter(typeof(NoConverter))]
    public Foo FooAsInteger get; set;

    public Foo FooAsString get; set;



    Then



    var root = new RootObject FooAsInteger = Foo.B, FooAsString = Foo.B ;

    var json = JsonConvert.SerializeObject(root, Formatting.Indented, new StringEnumConverter());

    Console.WriteLine(json);


    Produces the output




    "FooAsInteger": 1,
    "FooAsString": "B"



    Note that you can also apply NoConverter directly to the enum, if you want all occurrences of the enum in all data models to be serialized as an integer:



    [JsonConverter(typeof(NoConverter))]
    public enum FooAlwaysAsInteger A, B, C


    Sample fiddle.






    share|improve this answer


























      up vote
      3
      down vote



      accepted










      You could add a dummy converter to the properties in question that does nothing:



      public class NoConverter : JsonConverter

      public override bool CanConvert(Type objectType)

      // Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
      throw new NotImplementedException();


      public override bool CanRead get return false;

      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

      throw new NotImplementedException();


      public override bool CanWrite get return false;

      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

      throw new NotImplementedException();




      Then attach it to the property using [JsonConverter(typeof(NoConverter))]. Having done so, the JsonConverter attribute's converter supersedes the globally specified converter, but since CanRead and CanWrite both return false no conversion is performed. For collections of enums, you could use [JsonProperty(ItemConverterType = typeof(NoConverter))].



      For instance, if you define the types:



      public enum Foo A, B, C 

      public class RootObject

      [JsonConverter(typeof(NoConverter))]
      public Foo FooAsInteger get; set;

      public Foo FooAsString get; set;



      Then



      var root = new RootObject FooAsInteger = Foo.B, FooAsString = Foo.B ;

      var json = JsonConvert.SerializeObject(root, Formatting.Indented, new StringEnumConverter());

      Console.WriteLine(json);


      Produces the output




      "FooAsInteger": 1,
      "FooAsString": "B"



      Note that you can also apply NoConverter directly to the enum, if you want all occurrences of the enum in all data models to be serialized as an integer:



      [JsonConverter(typeof(NoConverter))]
      public enum FooAlwaysAsInteger A, B, C


      Sample fiddle.






      share|improve this answer
























        up vote
        3
        down vote



        accepted







        up vote
        3
        down vote



        accepted






        You could add a dummy converter to the properties in question that does nothing:



        public class NoConverter : JsonConverter

        public override bool CanConvert(Type objectType)

        // Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
        throw new NotImplementedException();


        public override bool CanRead get return false;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

        throw new NotImplementedException();


        public override bool CanWrite get return false;

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

        throw new NotImplementedException();




        Then attach it to the property using [JsonConverter(typeof(NoConverter))]. Having done so, the JsonConverter attribute's converter supersedes the globally specified converter, but since CanRead and CanWrite both return false no conversion is performed. For collections of enums, you could use [JsonProperty(ItemConverterType = typeof(NoConverter))].



        For instance, if you define the types:



        public enum Foo A, B, C 

        public class RootObject

        [JsonConverter(typeof(NoConverter))]
        public Foo FooAsInteger get; set;

        public Foo FooAsString get; set;



        Then



        var root = new RootObject FooAsInteger = Foo.B, FooAsString = Foo.B ;

        var json = JsonConvert.SerializeObject(root, Formatting.Indented, new StringEnumConverter());

        Console.WriteLine(json);


        Produces the output




        "FooAsInteger": 1,
        "FooAsString": "B"



        Note that you can also apply NoConverter directly to the enum, if you want all occurrences of the enum in all data models to be serialized as an integer:



        [JsonConverter(typeof(NoConverter))]
        public enum FooAlwaysAsInteger A, B, C


        Sample fiddle.






        share|improve this answer














        You could add a dummy converter to the properties in question that does nothing:



        public class NoConverter : JsonConverter

        public override bool CanConvert(Type objectType)

        // Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
        throw new NotImplementedException();


        public override bool CanRead get return false;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

        throw new NotImplementedException();


        public override bool CanWrite get return false;

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

        throw new NotImplementedException();




        Then attach it to the property using [JsonConverter(typeof(NoConverter))]. Having done so, the JsonConverter attribute's converter supersedes the globally specified converter, but since CanRead and CanWrite both return false no conversion is performed. For collections of enums, you could use [JsonProperty(ItemConverterType = typeof(NoConverter))].



        For instance, if you define the types:



        public enum Foo A, B, C 

        public class RootObject

        [JsonConverter(typeof(NoConverter))]
        public Foo FooAsInteger get; set;

        public Foo FooAsString get; set;



        Then



        var root = new RootObject FooAsInteger = Foo.B, FooAsString = Foo.B ;

        var json = JsonConvert.SerializeObject(root, Formatting.Indented, new StringEnumConverter());

        Console.WriteLine(json);


        Produces the output




        "FooAsInteger": 1,
        "FooAsString": "B"



        Note that you can also apply NoConverter directly to the enum, if you want all occurrences of the enum in all data models to be serialized as an integer:



        [JsonConverter(typeof(NoConverter))]
        public enum FooAlwaysAsInteger A, B, C


        Sample fiddle.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 9 at 23:18

























        answered Sep 28 '16 at 6:00









        dbc

        52.3k765116




        52.3k765116



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39738714%2fselectively-use-default-json-converter%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Ruanda

            Makov (Slowakei)

            Kleinkühnau