问题描述
我是C#和json对象的新手,我正尝试将我的网站从基于xml的配置文件迁移到基于json的配置文件.有没有一种方法可以加载.json文件,使其变成对象?我一直在搜索网络,但找不到.我已经将xml文件转换并另存为.json.我宁愿不使用第3方库.
I am new to c# and json objects and I am trying to move my website from xml based config files to json based ones. Is there a way to load in a .json file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the xml file converted and saved as a .json. I would rather not use a 3rd party library.
推荐答案
您 确实 应该使用已建立的库,例如Newtonsoft.Json (甚至Microsoft都将其用于MVC和WebAPI等框架),或者.NET的内置JavascriptSerializer .
You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.
以下是使用Newtonsoft.Json读取JSON的示例:
Here's a sample of reading JSON using Newtonsoft.Json:
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
这篇关于将.json文件加载到C#程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!