Question

I'm trying to deseralize some json into a collection (list), but I'm not sure which method will return a list of objects, or do I have to loop through something and copy it to my own list?

Can anyone tell me the syntax or method I should use for this.

I've created my object with some properties, so it's ready to be used to hold the data. (title,url,description)

I've tried this, but it doesn't seem quite right

 List<newsItem> test = (List<newsItem>)JsonConvert.DeserializeObject(Fulltext);
Was it helpful?

Solution

Did you try looking at the help?

http://james.newtonking.com/json/help/?topic=html/SerializingCollections.htm

string json = @"[
  {
    ""Name"": ""Product 1"",
    ""ExpiryDate"": ""\/Date(978048000000)\/"",
    ""Price"": 99.95,
    ""Sizes"": null
  },
  {
    ""Name"": ""Product 2"",
    ""ExpiryDate"": ""\/Date(1248998400000)\/"",
    ""Price"": 12.50,
    ""Sizes"": null
  }
]";

List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);

Console.WriteLine(products.Count);
// 2

Product p1 = products[0];

Console.WriteLine(p1.Name);
// Product 1

OTHER TIPS

I'm using those extension methods:

    public static string ToJSONArray<T>(this IEnumerable<T> list)
    {
        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(IEnumerable<T>));
        MemoryStream ms = new MemoryStream();
        s.WriteObject(ms, list);
        return GetEncoder().GetString(ms.ToArray());
    }

    public static IEnumerable<T> FromJSONArray<T>(this string jsonArray)
    {
        if (string.IsNullOrEmpty(jsonArray)) return new List<T>();

        DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(IEnumerable<T>));
        MemoryStream ms = new MemoryStream(GetEncoder().GetBytes(jsonArray));
        var result = (IEnumerable<T>)s.ReadObject(ms);
        if (result == null)
        {
            return new List<T>();
        }
        else
        {
            return result;
        }
    }

You need to decorate your Objects like this one:

[DataContract]
public class MyJSONObject
{
    [DataMember]
    public int IntValue { get; set; }
    [DataMember]
    public string StringValue { get; set; }
}

try using array instead of generic list. this may help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top