'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 1:[1]

You can convert the values list to string of Array by building a new Json, like the following code:

var objectValues = JsonConvert.DeserializeObject<IEnumerable<ClassA>>($"[{string.Join(",", values)}]");

I hope that will help you out.

Solution 2:[2]

public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> propertyBuilder,
    string columnType = null, string columnName = "", JsonSerializerSettings settings = null)
{
    var converter = new ValueConverter<T, string>(
        v => JsonConvert.SerializeObject(v, settings),
        v => JsonConvert.DeserializeObject<T>(v, settings));

    var comparer = new ValueComparer<T>(
        (l, r) => JsonConvert.SerializeObject(l, settings) == JsonConvert.SerializeObject(r, settings),
        v => v == null ? 0 : JsonConvert.SerializeObject(v, settings).GetHashCode(),
        v => JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(v, settings), settings));

    propertyBuilder.HasConversion(converter);
    if (columnType != null) propertyBuilder.HasColumnType(columnType);

    if (columnName == "")
        propertyBuilder.HasColumnName($"Json_{propertyBuilder.Metadata.Name}");
    else if (columnName != null)
        propertyBuilder.HasColumnName(columnName);

    propertyBuilder.Metadata.SetValueConverter(converter);
    propertyBuilder.Metadata.SetValueComparer(comparer);

    return propertyBuilder;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ali Chavoshi