Load JSON data stream from text file into objects

2020-03-30 08:46发布

问题:

I'm using Newtonsoft.Json.Linq and I'd like to load the data into objects (or structs) that I define and put the objects into a list or collection.

Currently I'm pulling out the JSON properties with indexes to the names.

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;

The object is defined as follows, and sometimes the JSON won't contain a value for a property:

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:

You can use 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);
}


回答2:

You can deserialize a JSON stream into real objects using the JsonSerializer class.

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