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.
- 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)
{
}
}
- 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();
}
}
- Create an environment provider.
public class MyEnvironment : IEnvironment
{
public bool IsProd()
{
return true;
}
}
- Then build the NSerializer.
NSerializer serializer = NSerializerBuilder.Build()
.WithCache(cache)
.WithConfigurationProvider(configurationProvider)
.WithEnvironment(environment)
.Get();
- 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);
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!"}