Given this class, I am trying to serialize but it isn't working.
using System.Text.Json;
public class Service
{
public Service() { }
public string service;
public string description;
}
Service c = new Service();
c.description = "desc";
c.service = "serv";
string x = JsonSerializer.Serialize<Service>(c);
Debugging I see x == "{}". What am I missing?
C# .net core 3.1
You are missing setter and getter
public class Service
{
public Service() { }
public string service {get; set;}
public string description {get; set;}
}
public class Service
{
public Service() { }
public string SomethingElse { get; set; }
public string Description { get; set; }
}
A couple of things about your class.
1) You will need getters and setters on your properties (as others have pointed out)
2) C# best practice is to capitalize the first letter of class properties.
3) You really don't want to use a property with the same name as the class name.
Service c = new Service
{
Description = "desc",
SomethingElse = "serv"
};
string x = JsonConvert.SerializeObject(c);
This code gives you this for x:
{"SomethingElse":"serv","Description":"desc"}
Note that when you create a new instance of a class and then immediately fill it up and assign values to the properties, it's best to use the Object Initializer approach.
So instead of this:
Service c = new Service();
c.description = "desc";
c.service = "serv";
It's best to do this:
Service c = new Service
{
Description = "desc",
SomethingElse = "serv"
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With