/NSerializer

.NET Core port of our framework agnostic YAML based Serializer for Java (https://github.com/webbeta/Serializer)

Primary LanguageC#MIT LicenseMIT

webBeta NSerializer

Build Status Codacy Badge GitHub license NuGet

What is webBeta NSerializer?

YML based serializer for .Net Core. Based on JMS serializer https://jmsyst.com/libs/serializer/master/reference/yml_reference

It is a fork of our YML based serializer for Java.

Steps to create a NSerializer instance.

  1. Create a cache provider.
public class MyCache : ICache
{
    public string Get(string key)
    {
        return null;
    }

    public void Set(string key, string content)
    {
    }

    public void Remove(string key)
    {
    }
}
  1. Create a configuration provider.
public class MyConfigurationProvider : IConfigurationProvider
{
    private readonly Dictionary<string, object> _conf;

    public MyConfigurationProvider(Dictionary<string, object> conf)
    {
        _conf = conf;
    }

    public bool GetBoolean(string key, bool defaultValue)
    {
        return !_conf.ContainsKey(key) ? defaultValue : bool.Parse(_conf[key].ToString());
    }

    public string GetString(string key, string defaultValue)
    {
        return !_conf.ContainsKey(key) ? defaultValue : _conf[key].ToString();
    }
}
  1. Create an environment provider.
public class MyEnvironment : IEnvironment
{    
    public bool IsProd()
    {
        return true;
    }
}
  1. Then build the NSerializer.
NSerializer serializer = NSerializerBuilder.Build()
        .WithCache(cache)
        .WithConfigurationProvider(configurationProvider)
        .WithEnvironment(environment)
        .Get();
  1. Optionally, add a logger instance:
public class MyLogger : ILogger
{    
    public Level GetLevel()
    {
        return Level.ERROR;
    }

    public void SetLevel(Level level) 
    {
    }

    public void Error(string message)
    {
    }
}

serializer.SetLogger(logger);

Quick examples

Class Foo:

namespace Foo.Bar
{
    public class Foo {
        
        private string bar = "foobar";

        public string AutoPropertyString { get; set; } = "Foo Autoproperty!";
        
        public string GetBar() {
            return bar;
        }
        
        public long GetCalc() {
            return 2 + 2;
        }
        
    }
}

Yml file (named Foo.Bar.Foo.yml):

Foo.Bar.Foo:
  virtual_properties:
    GetCalc:
      serialized_name: calc
      groups: [barGroup]
  properties:
    bar:
      groups: [fooGroup]
    AutoPropertyString:
      groups: [autoGroup]

Usage:

serializer.Serialize(fooInstance, "fooGroup", "barGroup", "autoGroup");

// it will return
// {"bar": "foobar", "calc": 4, "autoPropertyString": "Foo Autoproperty!"}

License

MIT