Convert Json String to C# object

Let’s say we have this json string in Ajax post method;

let groupObject = '[{ "Key": "Commercial", "IsMember": "true" }, { "Key": "Corporate", "IsMember": "false" }, { "Key": "Consumer", "IsMember": "false" }]';

Make sure this is a valid json. We can use following web site for json validation;

https://jsonlint.com/

We will create a user group class in .NET;

public class UGroupVM
{
    public string? Key { get; set; }
    public string? IsMember { get; set; }
}

We will user JSON Deserialization to get group object (try to use IList or List otherwise deserialization will fail because json is formatted as key/value pair);

var userGroup = JsonSerializer.Deserialize<List<UserGroupVM>>(groupObject);

For Newtonsoft, this is the syntax

var userAdGroup =
 JsonConvert.DeserializeObject<List<UserGroupVM>>(groupObject);

An alternative is this;

JArray jarray = JArray.Parse(groupObject);

foreach (JObject jObject in jArray)
{
    Console.WriteLine($"{(string)jObject["Key"]} -> {(string)jObject["IsMember"]}");
}

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect