Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JsonSerializer give empty? [duplicate]

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

like image 817
Alan Baljeu Avatar asked May 17 '26 16:05

Alan Baljeu


2 Answers

You are missing setter and getter

public class Service
{
    public Service() { }
    public string service {get; set;}
    public string description {get; set;}
}
like image 65
Roman.Pavelko Avatar answered May 20 '26 05:05

Roman.Pavelko


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"
};
like image 34
Casey Crookston Avatar answered May 20 '26 06:05

Casey Crookston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!