Search code examples
c#asp.netjsonjson.net

Newtonsoft.json ignore Json property attributes


Newtonsoft.Json ignore JsonProperty attributes while serializing object to json in .NET Framework 4.5 legacy webapi project.

Properties in my class looks as simple as this:

using Newtonsoft.Json;

public class A
{

    [JsonProperty(PropertyName = "workflow")]
    public string Workflow { get; private set; }

}

Then i am executing serializing:

using Newtonsoft.Json;

var asJson = JsonConvert.SerializeObject(
    a,
    Formatting.None,
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

And output looks like this:

{
    "Workflow": "18",
}

instead of:

{
    "workflow": "18"
},

Based on JsonProperty. My question is, why newtonsoft serializer ignore Jsonproperty attributes in .NET Framework 4.5 web api project?


Solution

  • you examples are not valid, this is working for me

        var a = new A {Workflow="18"};
    
        var asJson = JsonConvert.SerializeObject(
            a,
            Newtonsoft.Json.Formatting.None,
            new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });
    }
    
    
    public class A
    {
        [JsonProperty(PropertyName = "workflow")]
        public string Workflow { get;  set; }
    }
    

    result

    {"workflow":"18"}
    

    the same is with this class

    public class A
    {
        [JsonProperty(PropertyName = "workflow")]
        public string Workflow { get; private set; }
        
        public A(string workflow)
        {
            Workflow=workflow;
        }
    }