Unexpected character encountered while parsing value
Asked Answered
S

22

177

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?

Selfabnegation answered 24/4, 2014 at 3:16 Comment(5)
Do you always face this issue no matter what the data? Once when I faced such an issue, the reason was that the service was sending invalid UTF-8 characters.Shaunshauna
@Shaunshauna just forgot to read in the files ... my faultSelfabnegation
assuming that is not a problem, what else? recv Exception-> {"topic":"robot1/Log","Msg":"Pilot Running"} Unexpected character encountered while parsing value: o. Path '', line 0, position 0.Reprobation
I solved this issue by adding [FromBody] to post method.Denizen
I was just pulling my hair out why I was running into the same issue.... yeah, forgot to read the file and that JsonConvert.DeserializeObject<> doesn't read the file for you. Thanks.Rasberry
L
207

Based on the line 0, position 0 information from your error code, it's likely that you are not passing (valid) 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.

Latterday answered 24/4, 2014 at 3:23 Comment(1)
I was using JsonConvert.DeserializeObject to deserialize response which is string and not json. Hence it was throwing the above error.Whack
M
100

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://jsonformatter.org/json-to-csharp

The simple code:

RootObject rootObj= JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(pathFile));
Minotaur answered 4/3, 2016 at 21:2 Comment(0)
R
27

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

enter image description here

Right answered 29/12, 2019 at 19:19 Comment(3)
I had a similar problem—but VS2019 parsing the launchSettings.json file—and had to change it from UTF-8-BOM to UTF-8.Incidental
If you are lucky enough to be the person who is writing the JSON, you can prevent the BOM from being written like so: "using (var streamWriter = new StreamWriter(someStream, new UTF8Encoding(false))) ..."Trawick
This was the case in my issue as well. And there was one more issue after this. The JSON parsed was not matching with my BaseObject.Clare
W
20

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

Wanids answered 18/2, 2017 at 8:51 Comment(0)
H
18

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)
Honeysweet answered 23/11, 2019 at 9:51 Comment(2)
It was a headache for me too, but it makes sense because every json is a key-value pair and you should provide a class with properties as keys to correctly map json to an instance of that classKocher
This deserves more than 1 upvote from me! I spend hours and considered abandonment of a particular exercise before stumbling on your tip.Guinness
S
8

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);

Shunt answered 1/2, 2018 at 8:34 Comment(0)
O
6

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 () {
        
}
Orthochromatic answered 17/4, 2019 at 11:57 Comment(1)
I'm late to the party on this, but this was my issue as well. When examining the "json" going into my Deserialize method, it showed it was trying to authenticate with the API.Glycoprotein
W
3

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);
           }
Wallis answered 12/11, 2019 at 16:4 Comment(0)
A
3

I ran into this issue and it ended up being because of BOM characters in my input string.

Here's what I ended up doing:

String.Trim(new char[] { '\uFEFF', '\u200B' });

This resolved the issue for me.

Aretha answered 26/10, 2021 at 15:21 Comment(0)
W
2

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

var result = client.DownloadData(url);
Whitleather answered 23/3, 2017 at 20:8 Comment(0)
E
1

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.

Effluent answered 2/5, 2019 at 11:31 Comment(0)
I
1

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.

Incompletion answered 22/7, 2019 at 16:6 Comment(0)
M
1

In my case, I was calling the async service method without using await, so before Task is completed I was trying to return the result!

Moil answered 1/3, 2022 at 0:53 Comment(0)
B
1

I had simular problem. In my case the problem was in DateTime format. It was just numbers and it is also know as EpochFormat or UnixTimestamp. A part from my JSON:

"direction": "outbound",
"date_archive": 1554691800224,
"date_doc": 1524700800000,
"date_sent": 1524704189000,
"date_received": 1524704189000,
"date_store_till": 1712544600224,

So I've used an attribute like this:

[JsonProperty("date_received")]
[JsonConverter(typeof(MicrosecondEpochConverter))]
public DateTime? DateReceived { get; set; }

You can find MicrosecondEpochConverter code here: https://mcmap.net/q/144244/-how-to-deserialize-a-unix-timestamp-μs-to-a-datetime-from-json

Berezniki answered 6/4, 2022 at 20:26 Comment(0)
T
1

Note that maybe your JSON contain extra " " in the values.

Typhoon answered 1/5, 2023 at 11:33 Comment(0)
N
0

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

Noontime answered 7/9, 2018 at 6:42 Comment(0)
E
0

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.

Ethnocentrism answered 1/2, 2019 at 2:56 Comment(0)
A
0

In my case, it was the lack of a default parameterless constructor !!!

Atheistic answered 14/1, 2022 at 23:17 Comment(0)
C
0

I've been struggling with this issue for over a week. After exhausting every thread and chatGPT answer, I finally figured it out.

I have a Blazor Server application that access a WebAPI 2.0 endpoint via httpclient to get a list of inventory item id's and descriptions. The application worked fine from Visual Studio accessing the published API endpoint. The API worked fine from Swagger. It would generate {"Unexpected character encountered while parsing value: e. Path '', line 0, position 0."} on using the published Blazor Server application. Both the API and Blazor Server app are hosted on same IIS server with different ports.

After reviewing the API IIS logs, I did not see the request coming from the httpclient in the Blazor Server app. I was accessing the API via a FQDN on our local intranet. I tried pinging the FQDN from the server and the ip being returned was ::1: which indicated it was using IPV6. I had IPV6 unchecked on the adapter's properties. After some research, I discovered unchecking IPV6 on the adapter's properties DOES NOT disable IPV6. Using Guidance for configuring IPv6 in Windows for advanced users, I added the registry entry to disable IPV6. Viola IT IS NOW WORKING!!

Caldeira answered 26/12, 2023 at 22:19 Comment(0)
T
-1

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.

Tyeshatyg answered 7/11, 2020 at 9:13 Comment(0)
F
-2

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

Foldaway answered 11/5, 2016 at 7:35 Comment(2)
Hi, I am using JsonConvert.SerializeObject, which will produce the first result form me, how do I get the second one ?Thorin
This does not answer the question that was asked.Brainchild
S
-2

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

Simone answered 26/9, 2016 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.