c# - 使用 JSON 将数据存储在文本文件中

标签 c# .net json

我需要在一些文本文件、客户和书籍中存储与图书馆相关的一些数据。 我一直在搜索如何使用 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/

相关文章:

c# - 处理进入故障状态的持久性 WCF 客户端

c# - 在 WPF 中的两个窗口之间切换

c# - 连接泄漏可能会导致超时过期。从池中获取连接之前超时时间已过?

java - 无法使用 JSON 和 JQuery 显示从 Spring MVC Controller 返回的响应

java - 将 JSON 解析为 java 对象

c# - Internet Explorer 不会在测试期间启动新窗口

c# - 绑定(bind)命令未执行

c# - 转换成 "object"类型的目的是什么?

.net - Teamcity 未满足要求 : MSBuildTools12. 0_x86_Path 存在

rvest 1.0.0 - 最新更新不兼容