1

I want to create my own Serializer from scratch for c#, I'm familiar with newtonsoft and other c# serializes but want to avoid using them (trying to remove dependencies in my project) I know that Json is just a string, so I can append strings but I want to use classes.

For example, I have a simple class here and I want to create a JSON.

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}


Account account = new Account
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

string json = JsonConvert.SerializeObject(account, Formatting.Indented); // Want to create alternative for this line.

Is there a recommended way to achieve it? Any references will be helpful, I failed to find anything relevant.

InUser
  • 1,138
  • 15
  • 22
  • 1
    look C# Reflection – TimChang Jun 02 '20 at 06:00
  • 3
    Does this answer your question? [How to parse JSON without JSON.NET library?](https://stackoverflow.com/questions/9573119/how-to-parse-json-without-json-net-library) – HariHaran Jun 02 '20 at 06:00
  • 2
    If you use dotnet core, you could use [microsofts own json serializer](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis) – Volkmar Rigo Jun 02 '20 at 06:03
  • 1
    [Not invented here](https://en.wikipedia.org/wiki/Not_invented_here). Building your own library is not worth the time and effort unless you have very clear and concrete goals and metrics for how your library will be an improvement over the others' implementation. – madreflection Jun 02 '20 at 06:05
  • 1
    If I understand your question correctly, you want to achieve this "from scratch"? Without any other dependency? If this correct, this is a missive under taking, assuming you want to do so generically at not for a small number of simple classes. Without giving it too much thought, you will need to use reflection, recursively, to deconstruct the target type to a single dimension (serialized) collection of objects that can be expressed as string. You will likely need to implement customer property attributes to describe the desired behavior also. – George Kerwood Jun 02 '20 at 06:05
  • @GeorgeKerwood, yes exactly what I wanted, thank you for the clarification, and summarized explanation! – InUser Jun 02 '20 at 06:10
  • @madreflection point taken ;) – InUser Jun 02 '20 at 06:10
  • There is also a [`JavaScriptSerializer`](https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer?view=netframework-4.8) out of the box in old .NET FW – Pavel Anikhouski Jun 02 '20 at 07:18

0 Answers0