0

When trying to Serialize a model which has data stored in fields System.Net.Http.Json is outputting an empty JSON Object. It works only when I use property with getters and setters.

I tried looking into what's the difference between the two, but I couldn't find anything that might affect their serializability

Consider the following class

public class User
{
    public int Id;
    public string Name;
    public string Username;
    public string Email;
}

When trying to Serialize an object of this call through JsonSerializer.Serialize we get {} as the output

var user = new User()
{
    Id = 12,
    Name = "user",
    Username = "username",
    Email = "[email protected]"
};

var jsonString = JsonSerializer.Serialize(user);
Console.WriteLine(jsonString);

Only when I update the User model to use properties with getters and setters JsonSerializer.Serialize works as expected.

public class User
{
    public int Id { get; set; }
    public string Name {g et; set; }
    public string Username { get; set; }
    public string Email { get; set; }
}

After this change, we get the following output {"Id":12,"Name":"user","Username":"username","Email":"[email protected]"}

HttpClient and HttpContent extension methods
Following the above MSDN tutorial and converted the properties to fields and it broke the deserialization as well in this case.

2
  • 1
    Not serializing fields is expected behavior. Are you just looking for something like this? Commented Jul 22, 2024 at 14:04
  • Okay Thanks! This makes sense since I recently upgraded my project from .NET framework 4.8 to .NET 8 hence I am seeing this change in serialization Commented Jul 22, 2024 at 14:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.