Unexpected character encountered while parsing value

zAfLu picture zAfLu · Apr 24, 2014 · Viewed 457.2k times · Source

Currently I have some issues. I'm using C# with Json.NET. The issue is that I always get:

{"Unexpected character encountered while parsing value: e. Path '', line 0, position 0."}

So the way I'm using Json.NET is the following. I have a Class which should be saved. The class looks like this:

public class stats
{
    public string time { get; set; }
    public string value { get; set; }
}

public class ViewerStatsFormat
{
    public List<stats> viewerstats { get; set; }
    public String version { get; set; }

    public ViewerStatsFormat(bool chk)
    {
        this.viewerstats = new List<stats>();
    }
}

One object of this class will be filled and saved with:

 File.WriteAllText(tmpfile, JsonConvert.SerializeObject(current), Encoding.UTF8);

The saving part works fine and the file exists and is filled. After that the file will be read back into the class with:

    try 
{ 

    ViewerStatsFormat current = JsonConvert.DeserializeObject<ViewerStatsFormat>(tmpfile);
    //otherstuff        

}
catch(Exception ex)
{
    //error loging stuff
}

Now on the current= line comes the exception:

{"Unexpected character encountered while parsing value: e. Path '', line 0, position 0."}

I dont know why this comes. The json file is the following -> Click me im the JSON link

Does anyone have any ideas?

Answer

Alexei Levenkov picture Alexei Levenkov · Apr 24, 2014

Possibly you are not passing JSON to DeserializeObject.

It looks like from File.WriteAllText(tmpfile,... that type of tmpfile is string that contain path to a file. JsonConvert.DeserializeObject takes JSON value, not file path - so it fails trying to convert something like @"c:\temp\fooo" - which is clearly not JSON.