首先需要在程序中定义一个和JSON格式相同的类
比如如下的JSONConfig 里面可以定义JSON对象中的各种属性
public class JSONConfig
{
}
然后我们就可以快速的读取文件中的数据
方法一
JSONConfig Config = new JSONConfig();
string FilePath = string.Empty;//文件的路径 一遍为json 或者txt文件
using (System.IO.StreamReader file = System.IO.File.OpenText(FilePath))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
var o = (JObject)JToken.ReadFrom(reader);
Config = o.ToObject<JSONConfig>();
}
}
方法二:
JSONConfig Config = new JSONConfig();
string FilePath = string.Empty;//文件的路径 一遍为json 或者txt文件
StreamReader sr = new StreamReader(FilePath, Encoding.GetEncoding("gb2312"));
string content = sr.ReadLine();//如果使用这种方法要根据实际情况读取所有的行
sr.Dispose();
Config = JsonConvert.DeserializeObject<JSONConfig>(content);
以上是提供的两种读取文件转换为对象类的方法