Runtime: In async the System.Text.Json throw "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."

Created on 25 Sep 2019  路  5Comments  路  Source: dotnet/runtime

The code like this:

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            var type = typeof(TestModel);
            var testModel = new TestModel {Id = Guid.NewGuid(), Name = "Test"};

            await using var ms = new MemoryStream();
            await JsonSerializer.SerializeAsync(ms, testModel, type);
            var result = await JsonSerializer.DeserializeAsync(ms, type);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}

public class TestModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
area-System.Text.Json

Most helpful comment

This is a bug in the repro. Serializing to the stream leaves the stream positioned at the end, so when you go to deserialize it, there's nothing to deserialize. You need to add a line like:
C# ms.Position = 0;
after you serialize and before you deserialize.

All 5 comments

This is a bug in the repro. Serializing to the stream leaves the stream positioned at the end, so when you go to deserialize it, there's nothing to deserialize. You need to add a line like:
C# ms.Position = 0;
after you serialize and before you deserialize.

@stephentoub Has this issue been fixed in 5.0? I am facing the similar issue in the following case:

string responseString = await response.Content.ReadAsStringAsync();  // Here responseString is a empty string
EmployeeDetailsViewModel employee = JsonSerializer.Deserialize<EmployeeDetailsViewModel>(responseString, JsonSerializerOptions);

What is the workaround for deserializing the empty string to null object in the above case?

Thank you.

Note: I am using .NET Core 3.1

Has this issue been fixed in 5.0?

I'm not sure what issue you're referring to. The problem covered by this issue was a bug in the poster's repro, not in System.Text.Json.

If you're facing problems, can you open a new issue with details, including a repro?

Thanks.

@stephentoub Here is the new issue I have submitted: [System.Text.Json] Empty string is not deserializing to null

Thank you.

@TanvirArjel this issue is not actually related to yours, here the problem is that the stream needs to be positioned back to the beginning after serializing.

https://github.com/dotnet/runtime/issues/34310 is about ASP.NET returning No Content for a null object.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

omajid picture omajid  路  3Comments

noahfalk picture noahfalk  路  3Comments

matty-hall picture matty-hall  路  3Comments

jzabroski picture jzabroski  路  3Comments

Timovzl picture Timovzl  路  3Comments