[c#] Unexpected character encountered while parsing value

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 don't know why this comes. The JSON file is the following -> Click me I am the JSON link

Does anyone have any ideas?

This question is related to c# json visual-studio-2013 json.net

The answer is


In my case, the file containing JSON string had BOM. Once I removed BOM the problem was solved.

enter image description here


I solved the problem with these online tools:

  1. To check if the Json structure is OKAY: http://jsonlint.com/
  2. To generate my Object class from my Json structure: https://www.jsonutils.com/

The simple code:

RootObject rootObj= JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(pathFile));

I have also encountered this error for a Web API (.Net Core 3.0) action that was binding to a string instead to an object or a JObject. The JSON was correct, but the binder tried to get a string from the JSON structure and failed.

So, instead of:

[HttpPost("[action]")]
public object Search([FromBody] string data)

I had to use the more specific:

[HttpPost("[action]")]
public object Search([FromBody] JObject data)

I had a similar error and thought I'd answer in case anyone was having something similar. I was looping over a directory of json files and deserializing them but was getting this same error.

The problem was that it was trying to grab hidden files as well. Make sure the file you're passing in is a .json file. I'm guessing it'll handle text as well. Hope this helps.


Please check the model you shared between client and server is same. sometimes you get this error when you not updated the Api version and it returns a updated model, but you still have an old one. Sometimes you get what you serialize/deserialize is not a valid JSON.


This error occurs when we parse json content to model object. Json content type is string. For example: https://dotnetfiddle.net/uFClKj Some times, an api that we call may return an error. If we do not check the response status, but proceed to parse the response to model, this issue will occur.


I had the same problem with webapi in ASP.NET core, in my case it was because my application needs authentication, then it assigns the annotation [AllowAnonymous] and it worked.

[AllowAnonymous]
public async Task <IList <IServic >> GetServices () {
        
}

Suppose this is your json

{
  "date":"11/05/2016",
  "venue": "{\"ID\":12,\"CITY\":Delhi}"
}

if you again want deserialize venue, modify json as below

{
  "date":"11/05/2016",
  "venue": "{\"ID\":\"12\",\"CITY\":\"Delhi\"}"
}

then try to deserialize to respective class by taking the value of venue


I experienced the same error in my Xamarin.Android solution.

I verified that my JSON was correct, and noticed that the error only appeared when I ran the app as a Release build.

It turned out that the Linker was removing a library from Newtonsoft.JSON, causing the JSON to be parsed incorrectly.

I fixed the error by adding Newtonsoft.Json to the Ignore assemblies setting in the Android Build Configuration (screen shot below)

JSON Parsing Code

static readonly JsonSerializer _serializer = new JsonSerializer();
static readonly HttpClient _client = new HttpClient();

static async Task<T> GetDataObjectFromAPI<T>(string apiUrl)
{
    using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
    using (var reader = new StreamReader(stream))
    using (var json = new JsonTextReader(reader))
    {
        if (json == null)
            return default(T);

        return _serializer.Deserialize<T>(json);
    }
}

Visual Studio Mac Screenshot

enter image description here

Visual Studio Screenshot

enter image description here


If you are using downloading data using url...may need to use

var result = client.DownloadData(url);

I faced similar error message in Xamarin forms when sending request to webApi to get a Token,

  • Make sure all keys (key : value) (ex.'username', 'password', 'grant_type') in the Json file are exactly what the webApi expecting, otherwise it fires this exception.

Unhandled Exception: Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0


This issue is related to Byte Order Mark in the JSON file. JSON file is not encoded as UTF8 encoding data when saved. Using File.ReadAllText(pathFile) fix this issue.

When we are operating on Byte data and converting that to string and then passing to JsonConvert.DeserializeObject, we can use UTF32 encoding to get the string.

byte[] docBytes = File.ReadAllBytes(filePath);

string jsonString = Encoding.UTF32.GetString(docBytes);


In my case, I was getting an error on JsonConvert.PopulateObject(). My request was returning JSON that was wrapped in an extra pair of '[ ]' brackets, making my result an array of one object rather than just an object. Here's what I did to get inside these brackets (only for that type of model):

           T jsonResponse = new T();
                var settings = new JsonSerializerSettings
                {
                    DateParseHandling = DateParseHandling.DateTimeOffset,
                    NullValueHandling = NullValueHandling.Ignore,
                };
                var jRslt = response.Content.ReadAsStringAsync().Result;
                if (jsonResponse.GetType() == typeof(myProject.Models.myModel))
                {
                    var dobj = JsonConvert.DeserializeObject<myModel[]>(jRslt);
                    var y = dobj.First();
                    var szObj = JsonConvert.SerializeObject(y);
                    JsonConvert.PopulateObject(szObj, jsonResponse, settings);
                }
                else
                {
                    JsonConvert.PopulateObject(jRslt, jsonResponse);
                }

When I encountered a similar problem, I fixed it by substituting &mode=xml for &mode=json in the request.


In my scenario I had a slightly different message, where the line and position were not zero.

E. Path 'job[0].name', line 1, position 12.

This was the top Google answer for the message I quoted.

This came about because I had called a program from the Windows command line, passing JSON as a parameter.

When I reviewed the args in my program, all the double quotes got stripped. You have to reconstitute them.

I posted a solution here. Though it could probably be enhanced with a Regex.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to visual-studio-2013

Microsoft Advertising SDK doesn't deliverer ads Visual Studio 2013 error MS8020 Build tools v140 cannot be found Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10) 'cannot find or open the pdb file' Visual Studio C++ 2013 Force uninstall of Visual Studio How to enable C# 6.0 feature in Visual Studio 2013? Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed Process with an ID #### is not running in visual studio professional 2013 update 3 Error C1083: Cannot open include file: 'stdafx.h' The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

Examples related to json.net

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path Return JsonResult from web api without its properties Checking for empty or null JToken in a JObject Send JSON via POST in C# and Receive the JSON returned? Unexpected character encountered while parsing value JSON.net: how to deserialize without using the default constructor? Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' Convert Json String to C# Object List