从文本文件加载JSON数据流为对象C# [英] Load JSON data stream from text file into objects C#
本文介绍了从文本文件加载JSON数据流为对象C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Newtonsoft.Json.Linq ,我想加载数据到对象(或结构),我定义并把对象变成列表或集合。
目前我拉出JSON性能与索引。名字
=文件名openFileDialog1.FileName;
StreamReader的重新= File.OpenText(文件名);
JsonTextReader读卡器=新JsonTextReader(重新);
串克拉=;
JArray根= JArray.Load(读卡器);
的foreach(JObject o在根目录)
{
CT + =\r\\\
HACCstudentBlogs.Add(\+(串)O [全名] +\\ \\,\\);;
}
namesText.Text =克拉;
对象定义如下,有时JSON将不包含一个属性值:
类blogEntry
{
公共字符串ID {搞定;组; }
公共字符串ContributorName {搞定;组; }
公共字符串名称{搞定;组; }
公共字符串描述{搞定;组; }
公共字符串CreatedDate {搞定;组; }
}
解决方案
您可以使用 JsonConvert.DeserializeObject< T>
:
[TestMethod的]
公无效CanDeserializeComplicatedObject()
{
变种进入=新BlogEntry
{
ID =0001,
ContributorName =乔,
CreatedDate =系统.DateTime.UtcNow.ToString(),
标题=#1测试,
说明=测试的博客文章
};
JSON字符串= JsonConvert.SerializeObject(输入);
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);
}
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; }
}
解决方案
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);
}
这篇关于从文本文件加载JSON数据流为对象C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文