2010-10-20 121 views
1

我使用Newtonsoft.Json.Linq,我想將數據加載到我定義的對象(或結構體)中,並將這些對象放入列表或集合中。從文本文件加載JSON數據流到對象C#

目前我拉出的索引名稱的JSON屬性。

filename = openFileDialog1.FileName; 

StreamReader re = File.OpenText(filename); 
JsonTextReader reader = new JsonTextReader(re); 
string ct = ""; 

JArray root = JArray.Load(reader); 
foreach (JObject o in root) 
{ 
    ct += "\r\nHACCstudentBlogs.Add(\"" + (string)o["fullName"] + "\",\"\");"; 
} 
namesText.Text = ct; 

的對象被定義如下,並且有時JSON將不包含的屬性值:

class blogEntry 
{ 
    public string ID { get; set; } 
    public string ContributorName { get; set; } 
    public string Title { get; set; } 
    public string Description { get; set; } 
    public string CreatedDate { get; set; } 
} 
+1

請告訴我問題嗎? – 2010-10-20 00:24:25

+0

此外,這些屬性可能是自動屬性,而不是由專用字段支持。 – 2010-10-20 00:28:23

+0

問題是如何將jSON對象放入我的對象的實例中? – Caveatrob 2010-10-20 00:31:25

回答

3

您可以使用JsonConvert.DeserializeObject<T>

[TestMethod] 
public void CanDeserializeComplicatedObject() 
{ 
    var entry = new BlogEntry 
    { 
     ID = "0001", 
     ContributorName = "Joe", 
     CreatedDate = System.DateTime.UtcNow.ToString(), 
     Title = "Stackoverflow test", 
     Description = "A test blog post" 
    }; 

    string json = JsonConvert.SerializeObject(entry); 

    var outObject = JsonConvert.DeserializeObject<BlogEntry>(json); 

    Assert.AreEqual(entry.ID, outObject.ID); 
    Assert.AreEqual(entry.ContributorName, outObject.ContributorName); 
    Assert.AreEqual(entry.CreatedDate, outObject.CreatedDate); 
    Assert.AreEqual(entry.Title, outObject.Title); 
    Assert.AreEqual(entry.Description, outObject.Description); 
} 
11

可以反序列化JSON流引入使用JsonSerializer類的真實對象。

var serializer = new JsonSerializer(); 
using (var re = File.OpenText(filename)) 
using (var reader = new JsonTextReader(re)) 
{ 
    var entries = serializer.Deserialize<blogEntry[]>(reader); 
}