Home > OS >  check if nested Object conatins any null value properties
check if nested Object conatins any null value properties

Time:02-02

I have a result response object which i have Deserialized and converted to a Json object which looks like

code looks like below

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

and deviceSeqNrResponse looks like

  {{
  "dataModelVersion": 1,
  "deviceIdentifier": "myDeviceID",
  "sequenceNumbers": [
    {
      "consumingApplication": "Gateway",
      "configurationSequenceNumber": 8
    }
  ]
}}

and I am trying to test this logic to see if there is any properties in sequenceNumbers": [] 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 sequenceNumbers": [] equals to true.

CodePudding user response:

Check this example:

        string responseBody = @"{
            'dataModelVersion': 1,
            'deviceIdentifier': 'myDeviceID',
            'sequenceNumbers': [
                {
                    'consumingApplication': 'Gateway',
                    'configurationSequenceNumber': 8
                },
                null
            ]
        }";

        JToken token = JToken.Parse(responseBody);
        if (token.SelectToken("sequenceNumbers").Any(item=>item.Type == JTokenType.Null))
        {
            Console.WriteLine("found.");
        }
        else
        {
            Console.WriteLine("not found.");
        }

        JObject deviceSeqNrResponse = (JObject)token;

CodePudding user response:

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

  • Related