views:

154

answers:

3

Hi,

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);
A: 

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

Ozan BAYRAM
+1  A: 

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; }
}
Arthur
+1  A: 

Did you try looking at the help?

http://james.newtonking.com/projects/json/help/SerializingCollections.html

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
James Newton-King
Ah ha, thanks, I'll try this out.. did try looking through the documentation, but couldn't find this.
optician