在c#中解析JSON字符串,就像javascript或python一样

Parsing a JSON string in C# like javascript or python do

本文关键字:javascript 就像 python 一样 字符串 JSON      更新时间:2023-09-26

我正试图使程序需要从给定文件读取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。如果是这种情况,那么你应该试试。

具有以下特点:

  1. LINQ to JSON
  2. JsonSerializer用于快速将。net对象转换为JSON再返回
  3. 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);
}
相关文章: