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.