Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings

后端 未结 1 718
孤城傲影
孤城傲影 2020-11-29 09:28

I\'m trying to serialize an object using Newtonsoft Json.Net.

This object is an anonymous type filled with a lot of heterogenous things, mainly regular POCOs, but al

相关标签:
1条回答
  • 2020-11-29 09:59

    A "null" value in a JObject is actually a non-null JValue with JValue.Type equal to JTokenType.Null. It represents a JSON value of null when such a value actually appears in the JSON. I believe it exists to capture the difference between the following two JSON objects:

      "source2": {
        "z": null
      }
    
      "source2": {
      }
    

    In the first case, the property "z" is present with a null JSON value. In the second case, the property "z" is not present. Linq-to-JSON represents the first case with a null-type JValue rather than having JProperty.Value actually be null.

    To prevent null tokens from creeping into your JObject's values, use the appropriate serializer setting when creating the JObject from some POCO:

    var jobj = JObject.FromObject(new
    {
        x = 1,
        y = "bla",
        z = (int?)null
    }, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore } );
    

    (Note the POCO must not itself already be a JObject. The untyped method(s) JsonConvert.DeserializeObject(jsonString) or JsonConvert.DeserializeObject<dynamic>(jsonString) will by default return a JObject when root JSON container in jsonString is a JSON object.)

    0 讨论(0)
提交回复
热议问题