将JSON数据流从文本文件加载到对象C#中

时间:2010-10-20 00:20:48

标签: c# json serialization poco

我正在使用Newtonsoft.Json.Linq,我想将数据加载到我定义的对象(或结构)中,并将对象放入列表或集合中。

目前我正在推出带有索引的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; }
}

2 个答案:

答案 0 :(得分:11)

您可以使用JsonSerializer类将JSON流反序列化为实际对象。

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

答案 1 :(得分: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);
}