jsonmicrosoft-graph-apimicrosoft-graph-sdkskiota

How to Deserialize a JSON Array into a List of Objects Using IParseNode in C#?


I'm working with the Microsoft Graph API and using the Kiota-generated models. I can successfully deserialize a single Participant entity from JSON using the following code:

IParseNode parseNode = new JsonParseNode(jsonString);
var participant = new Participant();
var fieldDeserializers = participant.GetFieldDeserializers();

foreach (var field in fieldDeserializers)
{
    var propertyParseNode = parseNode.GetChildNode(field.Key);
    if (propertyParseNode != null)
    {
        field.Value(propertyParseNode);
    }
}

However, I need to deserialize a JSON array into a List. I’m unsure how to modify this code to iterate over the array and deserialize each Participant object correctly.

What I have tried:

var participantsNode = parseNode.GetChildNode("participants");

foreach (var childNode in participantsNode.GetChildNode()) //There is no such property available on IParseNode


Solution

  • I would parse JSON string into JsonDocument and then call GetCollectionOfObjectValues on JsonParseNode.

    using var jsonDocument = JsonDocument.Parse(jsonString);
    var rootParseNode = new JsonParseNode(jsonDocument.RootElement);
    var participants = rootParseNode.GetCollectionOfObjectValues(Participant.CreateFromDiscriminatorValue);
    

    But it depends how your JSON string looks like.