Home > database >  C# convert IEnumerable to Array
C# convert IEnumerable to Array

Time:09-30

I have this code :

private static List<ParticipantJson> GetListParticipants(string dossierJson)
{
  dynamic participantsJson = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(dossierJson);
  IEnumerable<ParticipantJson>[] myList = participantsJson.Participants.ToString() as IEnumerable<ParticipantJson>[];
  var list = myList.ToList();
  return null;
}

the part of participantsJson.Participants.ToString() as IEnumerable<ParticipantJson>[]; in debugging mode shows the two json objects of the table Participants[0] and Participants1. as the next image. enter image description here

but the affectation IEnumerable[] myList is null.

How do i mess ?

CodePudding user response:

As mentioned using dynamic is not the best practice to deserialize json objects. Especially since .NET allows you to create classes that json can be mapped to.

public class ParticipantsJson
{
  public List<ParticipantJson> Participants { get; set; }
}

public class ParticipantJson
{
  public int DeltaParticipant { get; set; }
  //... remainder of JSON fields from JToken section in image
}

private static List<ParticipantJson> GetListParticipants(string dossierJson)
{
  var participantsJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ParticipantsJson>(dossierJson);
  return participantsJson.Participants;
}

That said you can still use dynamic in your function.

private static List<ParticipantJson> GetListParticipants(string dossierJson)
{
  dynamic participantsJson = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(dossierJson);

// this creates an array which to access you would need to loop through each object using a for loop.

var myList = new List<ParticipantJson>();

for(int i = 0; i < participantsJson.Count(); i  )
{
  var newParticipant = new ParticipantJson {
     DeltaParticipant = participantsJson[i].DeltaParticipant,
     //... remainder of JSON fields from JToken section in image
  };
  myList.add(newParticipant);
}

// or using foreach loop

foreach(var participant in participantsJson)
{
   var newParticipant = new ParticipantJson {
   DeltaParticipant = participant.DeltaParticipant,
     //... remainder of JSON fields from JToken section in image
   };
   myList.add(newParticipant);
}

  return myList;
}

CodePudding user response:

finally this code works for me.

private static List<ParticipantJson> GetListParticipants(string dossierJson)
{
  dynamic participantsJson = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(dossierJson);
  Newtonsoft.Json.Linq.JArray myList = participantsJson.Participants;
  var jTokens = myList.Select(x => x.ToString()).ToArray();
  List<ParticipantJson> participants = new List<ParticipantJson>();
  foreach (var token in jTokens)
  {
    ParticipantJson _tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<ParticipantJson>(token);
    participants.Add(_tmp);
  }
  return participants;
}

I fixed the issue.

  • Related