遇到jsonreaderexception意外字符 [英] jsonreaderexception unexpected character encountered

查看:2820
本文介绍了遇到jsonreaderexception意外字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用angular和C#的Web项目.
在C#控制器中,我想读取用于测试的本地json文件的内容.

I have a web project using angular and C#.
In a C# controller, I want to read in the contents of a local json file that is used for testing.

这是我运行以从工作目录中读取JSON的代码.

This is the code that I run to read the JSON from my working directory.

string path = HttpContext.Current.Server.MapPath("~/testing/testData.json");
JObject jsonData = JObject.Parse(path);
string jsonString = jsonData.ToString();
List<orResult> result = JsonConvert.DeserializeObject<List<orResult>>(jsonString);
return result;

可以在这里看到JSON. Json

The JSON can be seen here. Json

运行该应用程序时,出现以下错误.

When I run the app, I get the following error.

"Newtonsoft.Json.JsonReaderException"类型的异常发生在 Newtonsoft.Json.dll,但未在用户代码中处理

An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll but was not handled in user code

其他信息:解析时遇到意外字符 值:M.路径",第0行,位置0.

Additional information: Unexpected character encountered while parsing value: M. Path '', line 0, position 0.

当我将鼠标悬停在path变量上时,它指向正确的位置.如果将path变量复制并粘贴到浏览器中,则会看到JSON.错误是解析数据之类的东西……我不知道.需要帮助!

When I hover look at the path variable, it points to the right spot. If I copy and paste the path variable in to my browser, I see the JSON. The error is something with Parsing the data or something... I have no idea. Need help!

我已经查看了Stack上的其他解决方案,但没有一个解决了我的问题.

I've looked at other solutions on Stack and none of them resolved my problem.

推荐答案

JObject.Parse()需要实际的JSON内容(字符串),而不是路径.

JObject.Parse() expects the actual JSON content (string), not a path.

您的JSON实际上是一个数组,因此您可以使用JArray.Parse()代替.另外,将JSON字符串转换为JObject然后再返回ToString()的确不在此添加任何值".

Your JSON is really an array so you could use JArray.Parse() instead. Also, converting JSON string to JObject and then back ToString() is really not adding any "value" here.

这应该做到.

string json = File.ReadAllText(HttpContext.Current.Server.MapPath("~/testing/testData.json"));
var result = JsonConvert.DeserializeObject<List<orResult>>(json);

这篇关于遇到jsonreaderexception意外字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆