Home > front end >  How can i convert an array in Json string to c# object?
How can i convert an array in Json string to c# object?

Time:07-06

I have a json return result like the following:

Json =

{ "Id":"12345", "FirstName":"Bob", "LastName":"Builder", "Links":[] }

Links can have a list of objects of type LinkService, i want to cast even if the array is empty , so in c# i get an empty array.

I do the following

      var token = JObject.Parse(Json);
      var Id = token.Value<string>("Id");
      var fname = token.Value<string>("FirstName");
      var lbname = token.Value<bool>("LastName");
      var links = JsonSerializer.Deserialize<List<LinkService>>(token.Value<Array>("Links"));

Issue is that it says cant convert System.Array to Newtonsoft.Json.JsonReader

CodePudding user response:

You can convert the jToken to an object using the ToObject method:

var links = token["Links"].TObject<List<LinkService>>();
  • Related