Home > OS >  .Net System.Text.Json cannot serialize object
.Net System.Text.Json cannot serialize object

Time:11-30

I can't serialize BaseResponse<NoContent> object. But Device object serialized successfully. I didnt find reason

 var data = new BaseResponse<NoContent>();
 var json1 = JsonSerializer.Serialize(data);
 var data2 = new Device();
 var json2 = JsonSerializer.Serialize(data2);

BaseResponse Content :

public class BaseResponse<T> where T : class, new()
    {
        public BaseResponse()
        {
            Data = new T();
        }
        public T Data;

        public string Status = "Success";

        public List<string> Errors;

        public BaseResponse<T> AddError(string message)
        {
            Errors ??= new List<string>();
            Status = "Error";
            Errors.Add(message);
            return this;
        }
    }

Edit: Newtonsoft.Json can serialize both of them. I decided use Newtonsoft.

CodePudding user response:

you have to add getters and setters

public class BaseResponse<T> where T : class, new()
{
    public BaseResponse()
    {
        Data = new T();
    }
    public T Data {get; set;}

    public string Status  {get; set;} = "Success";

    public List<string> Errors {get; set;}

    public BaseResponse<T> AddError(string message)
    {
        Errors ??= new List<string>();
        Status = "Error";
        Errors.Add(message);
        return this;
    }
}

test


    var data = new BaseResponse<NoContent>();
    data.AddError("error message");
    var json1 = System.Text.Json.JsonSerializer.Serialize(data);

output

{
  "Data": {
    "Content": "No Content"
  },
  "Status": "Error",
  "Errors": [
    "error message"
  ]
}

NoContent class

public class NoContent
{
    public string Content {get; set;} ="No Content";
}

CodePudding user response:

What's missing is the option to include fields, by default System.Text.Json does not serialize fields, only properties.

You can change this behaviour by supplying JsonSerializerOptions, e.g:

var json1 = JsonSerializer.Serialize(data, new JsonSerializerOptions() { IncludeFields = true });
  • Related