C# 从 JsonReader 读取 JObject 时出错。路径 '',第 0 行,位置 0

hlh*_*406 6 c# json stream streamreader jsonreader

我正在尝试使用下面的代码解析我的 json。我收到错误:

从 JsonReader 读取 JObject 时出错。路径 '',第 0 行,位置 0。

我想这可能是因为我的 JSON 格式错误,所以我输出了它,看起来没问题:

{ 
    "serviceDeskId": "4", 
    "requestTypeId": "223", 
    "requestFieldValues": { 
        "summary": "test" 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

但现在我完全陷入困境了。谁能看到我哪里出错了?这真让我抓狂!!

正是在这一行触发了错误:

var jsonresponse = JObject.Parse(response);
Run Code Online (Sandbox Code Playgroud)

完整代码片段:

req.ContentType = "application/json";

                var json = JObject.Parse(
                        "{\"serviceDeskId\": \"4\",\"requestTypeId\": \"223\",\"requestFieldValues\": {\"summary\": \"" +
                        summary.Value + "\"}}");

                jsonCheck = json.ToString();

                using (var streamWriter = new StreamWriter(req.GetRequestStream()))
                    {

                        streamWriter.Write(json);
                    }

                    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;


                    // Obtain a 'Stream' object associated with the response object.
                    Stream ReceiveStream = resp.GetResponseStream();

                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                    String response = "";

                    // Pipe the stream to a higher level stream reader with the required encoding format. 
                    StreamReader readStream = new StreamReader(ReceiveStream, encode);

                    response = readStream.ReadToEnd();

                    // Release the resources of stream object.
                    readStream.Close();

                    // Release the resources of response object.
                    resp.Close();

                    var jsonresponse = JObject.Parse(response);
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

the*_*One 0

啊,我相信我以前也遇到过这个问题。我发现 Visual Studio 以不同的方式保存 json 文件。您可以通过以下方式检查:

  1. 在 Visual Studio 中,转到“文件”->“打开”并指向您的 json 文件
  2. 然后单击“打开”按钮附近的小箭头并选择“打开方式...”
  3. 当“打开方式”对话框打开时,选择“二进制编辑器”并单击“确定”

[注意:前面的步骤可以使用其他十六进制编辑器来完成。]

打开文件后,以十六进制格式查看它是否以以下形式开头...{.. 或结尾..}..,然后删除起始点“..”和结束点“..”,然后保存文件并重试。

如果您在 Visual Studio 中创建 json 文件,就会发生这种情况。

或者,您可以使用其他程序(如 Notepad ++)创建一个新文件并使用该文件。

希望这可以帮助。