Chris Barry
Chris Barry

Reputation: 4594

Json.net deseralize to a list of objects in c# .net 2.0

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

Upvotes: 6

Views: 9109

Answers (3)

James Newton-King
James Newton-King

Reputation: 49062

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

Upvotes: 6

Arthur
Arthur

Reputation: 8129

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; }
}

Upvotes: 1

Ozan BAYRAM
Ozan BAYRAM

Reputation: 2901

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

Upvotes: 0

Related Questions