skip to Main Content

I have managed to ignore the null buts but I have not been able to do the same with the empty strings. My project is an Azure Function running on .NET Core 3.1.

The configuration I have is the following in the startup

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json.Serialization;


builder.Services.AddMvcCore()
            .AddNewtonsoftJson(options =>
            {
                options.UseMemberCasing();
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
                options.SerializerSettings.Formatting = Formatting.Indented;
                options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            })
            .AddJsonOptions(option =>
            {
                option.JsonSerializerOptions.IgnoreNullValues = true;
                option.JsonSerializerOptions.WriteIndented = true;
                option.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
            });

Any idea why I don’t ignore empty strings?

3

Answers


  1. Chosen as BEST ANSWER

    The model that I am waiting for is the following

    {
    "product": {
        "id": 1,
        "name": "room_premium",
        "city": "medellin"
    },
    "parameters": [
        {
            "name": "PolicyHolder",
            "inputParameterId": 495,
            "inputParameterType": "Object",
            "inputParameterSchemaList": [
                {
                    "propertyId": "562",
                    "propertyName": "Birthdate",
                    "propertyValue": "",
                    "propertyTypeDescription": "Text",
                    "propertyTypeListValue": ""
                },
                {
                    "propertyId": "566",
                    "propertyName": "IdentificationNumber",
                    "propertyValue": "",
                    "propertyTypeDescription": "Text",
                    "propertyTypeListValue": ""
                }
            ]
        }
    ]}
    

    But I should ignore the

    "propertyValue": "",
    "propertyTypeListValue": ""
    

  2. Your settings seems to be correct.
    However you might need to decorate your properties with the Default value attribute for DefaultValueHandling.Ignore to kick in

    Below is a working sample

    static void Main()
    {
        var planet = new Planet();
    
        planet.planetName = "";
    
        var settings = new JsonSerializerSettings();
    
        settings.DefaultValueHandling = DefaultValueHandling.Ignore;
    
        Console.WriteLine(JsonConvert.SerializeObject(planet, settings));
    
    }
        
    public class Planet
    {
        public string planetID { get; set; } = Guid.NewGuid().ToString();
    
        [DefaultValue("")]
        public string planetName { get; set; }
    
    }
    

    Output : planetName property is ignored while serializing
    enter image description here

    EDIT :

    Tried to implement AZ function app with a startup file and added settings for serialization. But I found that adding newtonsoft serializer settings to builder services has no effect on serialization.

    Best workaround would be to add settings to function while serializing like below example from AZ function that i tried out.

     FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
    
            var content = await new StreamReader(req.Body).ReadToEndAsync();
            var settings = new JsonSerializerSettings();
    
            settings.DefaultValueHandling = DefaultValueHandling.Ignore;
            settings.NullValueHandling = NullValueHandling.Ignore;
            Planet deserializedPlanet = JsonConvert.DeserializeObject<Planet>(content);
    
            string stringified = JsonConvert.SerializeObject(deserializedPlanet,settings);
    
            string responseMessage = $"JSON serialized output{stringified}";
    
            return new OkObjectResult(responseMessage);
        }
    

    Input :
    enter image description here

    Output :

    enter image description here

    Login or Signup to reply.
  3. Maybe override the tostring method and pass in your JSON options there or just do some isnullorempty checks before you jsonStringify.
    or use

    [JsonProperty("{propertyname}",DefaultValueHandling = DefaultValueHandling.Ignore)]
    
    
    
    static void Main()
    {
        var planet = new Planet();
    
        planet.planetName = "";
    
        Console.WriteLine(planet.ToString());
    
    }
    
    public class Planet
    {
        public string planetID { get; set; } = Guid.NewGuid().ToString();
    
        // optionally use this if you want fine grain controll
        //[JsonProperty("planetName",DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string planetName { get; set; }
    
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this,
                                            new JsonSerializerSettings
                                            {
                                                NullValueHandling = NullValueHandling.Ignore,
                                                DefaultValueHandling = DefaultValueHandling.Ignore
                                            });
        }
    
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search