Search code examples
c#jsonjson.net.net-6.0json-deserialization

Check nested object contains any propeties with null value


I have a result response object which I need to deserialize and convert to a JSON object which looks like this:

var responseBody = await response.Content.ReadAsStringAsync();
var deviceSeqNrResponse = JsonConvert.DeserializeObject(responseBody);

and deviceSeqNrResponse looks like

{
    "dataMod": 1,
    "deviceId": "myDeviceID",
    "seqNum": [
      {
          "ApplicationType": null,
          "exampleId": 8
      }
    ]
}

and I am trying to test this logic to see if there are any properties in "seqNum": [] which is nested in the result object. I tried .Contains and other approaches with no success.

I am using .NET 6.

What I am trying to achieve is that:

Assert there is no property with null values in "seqNum": [] equals to true.


Solution

  • Approach 1: Wih Newtonsoft.Json

    1. Select the element "sequenceNumbers" via .SelectToken().

    2. Get all the values from 1 (return nested arrays). Flatten the nested array via .SelectMany().

    3. With .Any() to find any element from the result 2 with Type == JTokenType.Null.

    4. Negate the result from 3 to indicate there is no element with the value: null.

    JToken token = JToken.Parse(responseBody);
    
    bool hasNoNullValueInSeqNumber = !token.SelectToken("sequenceNumbers")                                                    
                                    .SelectMany(x => x.Values())
                                    .Any(x => x.Type == JTokenType.Null);
    

    Approach 2: With System.Reflection

    1. Get all the public properties from the SequenceNumber class.

    2. With .All() to evaluate all the objects in SequenceNumbers list doesn't contain any properties with value: null.

    using System.Linq;
    using System.Reflection;
    
    bool hasNoNullValueInSeqNumber = typeof(SequenceNumber).GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .All(x => !deviceSeqNrResponse.SequenceNumbers.Any(y => x.GetValue(y) == null));
    

    Demo @ .NET Fiddle