2009-12-21 18 views
6

Bazı jsonları bir koleksiyona (liste) ayırmaya çalışıyorum, ancak hangi yöntemin bir nesne listesi döndüreceğinden emin değilim. bir şeyleri karıştırıp kendi listeme kopyalamak zorunda mıyım?Json.net deseralize C# .net 2.0 nesnesinin bir listesi için

Bunun için kullanmam gereken sözdizimi veya yöntemi söyleyen var mı?

Nesnemi bazı özelliklerle oluşturdum, bu nedenle verileri tutmak için kullanılmaya hazır. (Başlık, url, açıklama)

Bu denedim ama

List<newsItem> test = (List<newsItem>)JsonConvert.DeserializeObject(Fulltext); 

cevap

5

yardım bakarak denediniz mi?

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 
+1

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

Ah ha, teşekkürler, .. belgelerine bakarak çalıştım bu denersiniz, ancak bu bulamadık. –

0

jenerik listenin yerine dizisi kullanarak deneyin çok doğru görünmüyor. Bu yardımcı olabilir.

1

O uzatma yöntemleri kullanıyorum: Sen gibi Nesneleri süslemek için ihtiyaç

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

bu bir:

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