JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.73k stars 3.25k forks source link

Newtonsoft.Json NullValueHandling.Ignor doesn't ignore null values #1493

Open AfshanJL opened 6 years ago

AfshanJL commented 6 years ago

I have this class with one optional field which I want to hide from JSON when it's null, but it's there even with a null value.

public partial class Library
{
    [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default)]
    public string Type { get; set; }

    [Newtonsoft.Json.JsonProperty("Value", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    public string Value { get; set; }

@JamesNK
wizofaus commented 6 years ago

Couldn't reproduce, could you include the code you used to serialize it?

AfshanJL commented 6 years ago

this is my setting _settings = new System.Lazy(() => { var settings = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(settings); return settings; });

var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(Request, _settings.Value));

wizofaus commented 6 years ago

Without knowing what "UpdateJsonSerializerSettings" is or even what "Request" is, that's not really enough to go on. If I just use a new object of type "Library" for Request and ignore UpdateJsonSerializerSettings, I get { "Type": null }, which would seem to be what you want.

Splitframe commented 6 years ago

This suddenly happens for me, also. Everything worked fine up until now null values were ignored without problems. I don't even know why this suddenly happens. It worked before and I have not touched that part of the code.

Exception:

Newtonsoft.Json.JsonSerializationException: 'Error converting value 0 to type 'System.Single[]'. Path '[43].coordinates', line 1, position 6953.'

JSON part of the offender:

[...] 
{"id":774,"name":"Konradhofer Catering - Betriebskantine IPP","city":"Garching bei München","address":"Gießenbachstraße, 85748 Garching bei München, Germany","coordinates":[48.2619774,11.6713921]} 
[...]

Json deserialization called with:

static JsonSerializerSettings settings = new JsonSerializerSettings() {

            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };

        public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content) {

            string json = await content.ReadAsStringAsync();
            json = json.Replace("null", "0");
            T value = JsonConvert.DeserializeObject<T>(json, settings);
            return value;
        }

Member in an unannotated POCO it should have been mapped to: public float[] coordinates;

Edit: Just after sending this I noticed the json.Replace. Without that part it works. It worked before with that part though.