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
Select the element "sequenceNumbers" via
.SelectToken()
.Get all the values from 1 (return nested arrays). Flatten the nested array via
.SelectMany()
.With
.Any()
to find any element from the result 2 withType == JTokenType.Null
.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
Get all the public properties from the
SequenceNumber
class.With
.All()
to evaluate all the objects inSequenceNumbers
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));