Load JSON data stream from text file into objects C#

18,257

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

Solution 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);
}
Share:
18,257
Caveatrob
Author by

Caveatrob

ASP.NET/C# Coder SQL Server Developer Writer Teacher

Updated on June 05, 2022

Comments

  • Caveatrob
    Caveatrob almost 2 years

    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; }
    }
    
    • Michael Shimmins
      Michael Shimmins over 13 years
      Also those properties could be auto properties rather than being backed by a private field.
    • Caveatrob
      Caveatrob over 13 years
      The question is how do I put the jSON object into an instance of my object?