Json bringing back unwanted properties

Keith Viking 20 Reputation points
2023-06-09T13:46:25.44+00:00

WebAPI Core (.Net 6)

I have a Model class which contains multiple properties. The properties can have empty values. Only the ones i need should be produced.

public class ClientFocus 
{     
    public string? Item {get; set;}     
    public string? ItemTwo {get; set;} 
} 
 

I add some data to it

var c = new ClientFocus 
{
    Item = "Hello"
};

client = ClientFocus(c); // code below

Note: Property ItemTwo is not filled in.

I pass this into the statusCode

return StatusCode(HttpStatusCode.BadRequest, client);

The above brings back all the Json including the empty property.

I then add a new method and pass in the above instance

private ClientFocus ClientFocus (ClientFocus data)
{
   var so = JsonConvert.SerializeObject(data, JsonSerializerSettings()
   {
       NullValueHandling = NullValueHandling.Ignore,
   });

  return JsConvert.DeserializeObject<ClientFocus>(so);
}

With the above change i can see the so object removes the property but i have to Deserilize it back and when i do this it re-adds the missing property (the one i dont need).

If i retrieve the string version of the data then its fine but then i lose the encoding and it comes as plain text.

Ive tried adding JsonIgnore attribute to the model but that made no difference either.

What have i done wrong?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,140 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,204 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,041 Reputation points
    2023-06-09T16:13:02.03+00:00

    unless you overrode the default serializer, .net 6 webapi uses system.text.json, not newtonsoft. you need to use the system.text.json options

    public class ClientFocus 
    {   
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]  
        public string? Item {get; set;}   
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]  
        public string? ItemTwo {get; set;} 
    } 
     
    

    Or you can config the default options at startup:

    builder.Services
        .AddControllers()
        .AddJsonOptions(o =>
        {
            o.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault;
        });