1 year ago

#70021

test-img

dzenesiz

Custom JSON Serialization in System.Text.Json

I am working on a project in .NET 6 and I need to serialize objects to JSON (and deserialize from JSON as well) in a specific way. These are the "rules":

  1. If a property is a nested object, and it's null, skip it entirely
  2. If a nested object has only null or empty values, skip it entirely
  3. If a property is a string, and it is null or empty, skip it entirely
  4. If a property is an empty IEnumerable, skip it entirely

Additionally, I'd like to avoid coupling my model to any concrete JSON serializer, so I'm trying to avoid using attributes. Lastly, I am looking for a generic serialization method.

So if I had a class like this one:

public class MyOuterClass
{
    public string Name { get; set; }
    public string Email { get; set; }
    public MyInnerClass InnerOne { get; set; }
    public MyInnerClass InnerTwo { get; set; }
    public List<YetAnotherClass> ListProp { get; set; } = new List<YetAnotherClass>();
}

public class MyInnerClass
{
    public string NameInner { get; set; }
}

And instantiated it like this:

var value = new MyOuterClass
{
    Name = "My Name",
    Email = "",
    InnerOne = null,
    InnerTwo = new MyInnerClass { NameInner = "" }
};

Calling something like:

_mySerializer.Serialize<MyOuterClass>(value);

Should return:

{
    name: "My Name"
}

Is there any way to achieve this only with System.Text.Json.Serialization or Newtonsoft.JSON? I'd like to avoid writing completely custom code with reflection and recursion.

c#

json

.net-core

serialization

system.text.json

0 Answers

Your Answer

Accepted video resources