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.
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));
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;