我需要在一些文本文件、客户和书籍中存储与图书馆相关的一些数据。 我一直在搜索如何使用 JSON 将数据保存到文本文件,但我无法理解代码或应该调用哪些命名空间。
我正在寻找典型的 JSON 结构,例如:
{
"name": "John Doe",
"address": "Street of whatever",
"ID": 123456789,
"telephone": 123443221,
"gender": "M",
"prefgenres": {
"adventure": true,
"romance": false,
"police": true,
"scifi": false
}
}
最佳答案
尝试使用 JSON.Net ,使用起来非常简单。
为了简化您的研究,如果您只想序列化一个简单的对象,您可以这样做:
using System.IO;
using Newtonsoft.Json;
namespace test
{
public void writeObject( object myObj){
using (StreamWriter myFile = new StreamWriter(myPath))
{
newFile.WriteLine(JsonConvert.SerializeObject(myObj));
}
}
}
要反序列化您的数据,您可以使用以下命令:
using System.IO;
using Newtonsoft.Json;
namespace test
{
public MyObject readObject(){
var result;
using (StreamReader file = new StreamReader(myPath))
{
result = JsonConvert.DeserializeObject<MyObject>(file.ReadToEnd());
file.Close();
}
return result;
}
} //Notice that "MyObject" could be even a collection of your objects, like List<Customer> and you can deserialize all in once.
关于c# - 使用 JSON 将数据存储在文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29572764/