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; }
}
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.
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.