代码之家  ›  专栏  ›  技术社区  ›  Caveatrob

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

  •  1
  • Caveatrob  · 技术社区  · 15 年前

    我在用 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 回复  |  直到 15 年前
        1
  •  3
  •   Michael Shimmins    15 年前

    你可以使用 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
  •  11
  •   Nathan Baulch    15 年前

    您可以使用 JsonSerializer 班级。

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