3

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.

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;

The JSON can be seen here. Json

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

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

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

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!

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

Frantumn
  • 1,725
  • 7
  • 36
  • 61

2 Answers2

3

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

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.


This should do it.

string json = File.ReadAllText(HttpContext.Current.Server.MapPath("~/testing/testData.json"));
var result = JsonConvert.DeserializeObject<List<orResult>>(json);
Mikko Viitala
  • 8,344
  • 4
  • 37
  • 62
  • 1
    Using [`JToken.ReadFrom()`](http://www.newtonsoft.com/json/help/html/ReadJson.htm) one can stream directly from the file without needing to load an intermediate string representation. – dbc Sep 02 '15 at 20:33
0

You are attempting to deserialize the translated path ("c:\whatever\...\testing\testData.json") that MapPath returns, i.e. not the content of the file.

Try something like this instead:

JObject jsonData = JObject.Parse(File.ReadAllText(path));

... but then again, there is no need to use Parse() as you don't need the JObject. Just deserialize directly to a List<orResult>:

var result = JsonConvert.DeserializeObject<List<orResult>>(File.ReadAllText(path));
Micke
  • 2,251
  • 5
  • 33
  • 48