views:

26

answers:

2

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

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);
}
Nathan Baulch
+2  A: 

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);
}
Michael Shimmins