在c#中解析JSON字符串,就像javascript或python一样
Parsing a JSON string in C# like javascript or python do
我正试图使程序需要从给定文件读取JSON数据。但是JSON文件可能非常复杂。下面是我使用的代码
static void Main(string[] args)
{
//step one: get a correct file path
string filepath = getFilePath("Please write here the path to your file");
//getFilePath is just a function I wrote to read user entry and automatically sanitize the string.
while (!File.Exists(filepath)) { filepath = getFilePath("The file path appears to be wrong, please correct."); }
//Setep 2: read the text of the file
string fileJSONString = File.ReadAllText(filepath);
//step 3: parse
object myDictionaryFromJSON = (new JavaScriptSerializer().DeserializeObject(fileJSONString));
object question1 = myDictionaryFromJSON.questions[0];
}
问题是Visual Studio给了我很多错误。我已经尝试使用Dictionary
而不是object
,但它仍然不工作的方式,我需要它的工作。例如,这实际上可以在python上工作。
myDictionaryFromJSON = json.loads(JSONtext);
question1 = myDictionaryFromJSON['questions'][0];
question1text = question1["theQuestion"];
question1options = question1["options"];
question1correctAnswer = question1["correctAnswer"];
这只是一个例子。问题是Python和javascript可以完美地处理json,并且非常擅长将json字符串转换为字典和对象。但是c#不起作用。我不知道该怎么办。我该怎么办呢?
我假设您没有使用Json.NET。如果是这种情况,那么你应该试试。
具有以下特点:
- LINQ to JSON JsonSerializer用于快速将。net对象转换为JSON再返回
- Json。. NET可以选择性地生成格式良好的缩进JSON调试或显示
看Json有多快。. NET与JavaScriptSerializer的比较:https://i.stack.imgur.com/T77y2.png
用c#加载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);
}
相关文章:
- 为什么可以'我们在函数体中为函数对象添加属性,就像在javascript中为对象文字添加属性一样
- 如何在javascript对象中设置属性的类型,就像mongoose模式设计一样
- 为什么javascript函数名称custom是一个小写的单词,后跟一个大写的单词,就像'orangeCost'一样
- 适应.js就像Javascript的功能一样
- 锚定标签功能强大,但滚动流畅赢得't工作;页面的行为就像javascript是'没有
- JAVASCRIPT-动画块消失,就像它出现时一样
- Jquery/javascript方式发送50个表单,就像发送1个表单一样
- emacs JavaScript字体锁定模式:希望突出显示'self'就像'这'
- Javascript查找匹配值的键,就像SQL中的查询一样
- Excel 就像 RoR 中的 JavaScript 编辑一样
- 在 JavaScript 中是否可以使用 @“text” 将多行字符串分配给变量,就像在 C# 中一样
- 如何使用jquery或javascript让图像从页面的一侧滑动到另一侧?就像在 thepiratebay.se 上一样
- 如何在 JavaScript 中将字符串更改为变量,就像 PHP 中的 $$ 一样
- 在 JavaScript 正则表达式中嵌入注释,就像在 Perl 中一样
- 如何将 Base64 字符串转换为 javascript 文件对象,就像从文件输入表单一样
- C++就像在Javascript中调试一样
- Javascript:在对象中快速查找值(就像我们可以查找属性一样)
- 多维数组与JavaScript就像php一样
- 如何在多迪姆数组中放置值 - 就像棋盘上的 6 个皇后 - javascript
- 有没有办法使用 javascript (jquery) 使元素的行为**完全**就像它被点击一样(一种独特的情况)