Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json.JsonException: The input does not contain any JSON tokens

I'm just trying to use a Http POST method in a Blazor app through

public async Task CreateUnit(UnitEntity unit)
{
    await _http.PostJsonAsync<UnitEntity>("api/units", unit);
}

_http and myObject have been defined elsewhere, but I'm getting this weird error. Can anyone help? This is the closest thing I could find elsewhere: https://github.com/dotnet/runtime/issues/30945.

The full error message is

System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

And it here's the stack

enter image description here

like image 593
Broad3857 Avatar asked Mar 10 '20 17:03

Broad3857


4 Answers

Another reason this error could pop up, as it did for me, is simply because the API endpoint doesn't exist because it was misspelled.

like image 141
Lukas Avatar answered Oct 20 '22 23:10

Lukas


I got a similar error in Program.cs Main method CreateHostBuilder(args).Build();:

System.FormatException: 'Could not parse the JSON file.'

JsonReaderException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0.

For me it turned out to be the local secrets.json file that not contained a valid json object.

https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#secret-manager

Because of this I could not see any errors in Git or rollback to a working commit since the file is not checked in.

Solved by adding an empty object to the file via Visual Studio - right click the project in solution explorer and select Manage User Secrets:

{

}

https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#manage-user-secrets-with-visual-studio

like image 42
Ogglas Avatar answered Oct 20 '22 21:10

Ogglas


In my case the code was doing this:

var json = await response.Content.ReadAsStringAsync();
var result = JsonObject.Parse(json); // threw the exception mentioned in the question

Why did that happen? That's because json value was an empty string "". Parse fails with an empty string.

Fixed it doing this simple change:

var json = await response.Content.ReadAsStringAsync();
var result = string.IsNullOrEmpty(json) ? null : JsonObject.Parse(json);
like image 2
Leniel Maccaferri Avatar answered Oct 20 '22 21:10

Leniel Maccaferri


i had similar issue and the problem to check if the json string you are readying is empty, null, or bad formatted. debug to the code line where you are reading data into string before deserialize or serialize call.

like image 1
Jabez Avatar answered Oct 20 '22 21:10

Jabez