开发者

Load JSON data stream from text file into objects C#

开发者 https://www.devze.com 2023-01-21 14:41 出处:网络
I\'m using Newtonsoft.Json.Linq and I\'d like开发者_JAVA百科 to load the data into objects (or structs) that I define and put the objects into a list or collection.

I'm using Newtonsoft.Json.Linq and I'd like开发者_JAVA百科 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; }
}


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号