Search code examples
c#.netjsonjsonconvert

Extension method for JSONConvert.Deserilize on collection of JSON object values


I have a situation where I have Json Values as List of string.

List<string> values = new List<string>()
{
    "{\"Id\":\"SC\",\"Value\":8563}",
    "{\"Id\":\"SC\",\"Value\":8563}",
    "{\"Id\":\"SC\",\"Value\":8563}"
};

How to I de-serialize into a List of Objects:

public class ClassA
{
   public string Id {get; set;}
   public int Value {get;set;}
}

var objectValues = JsonConvert.DeserializeObject<IEnumerable<ClassA>>(values);

I couldn't deserialize when I am passing values list and it is expecting a string as parameter; can I create an extension method or is there an easier way to deserizalize ?


Solution

  • Try this:

                List<ClassA> deserialized = new List<ClassA>();
                List<string> values = new List<string>()
                {   
                    "{\"Id\":\"SC\",\"Value\":8563}",
                    "{\"Id\":\"SC\",\"Value\":8563}",
                    "{\"Id\":\"SC\",\"Value\":8563}"
                };
                foreach (var item in values)
                {
                    var objectValue = JsonConvert.DeserializeObject<ClassA>(item);
                    deserialized.Add(objectValue);
                }
    

    And as extension:

     public static List<ClassA> ToClassA(this List<string> stringList)
        {
            List<ClassA> deserialized = new List<ClassA>();
            foreach (var item in stringList)
            {
                var objectValue = JsonConvert.DeserializeObject<ClassA>(item);
                deserialized.Add(objectValue);
            }
            return deserialized;
        }
    

    Generic extension

    public static List<T> ToList<T>(this List<string> stringList) where T : class
            {
                List<T> deserialized = new List<T>();
                foreach (var item in stringList)
                {
                    var objectValue = JsonConvert.DeserializeObject<T>(item);
                    deserialized.Add(objectValue);
                }
                return deserialized;
            }
    

    use:

    var result = values.ToList<ClassA>();