Json.NET是否有流畅的转换器/映射器?

14

所以,我有一堆需要序列化/反序列化的类,它们也恰好是领域对象(至少其中的一些),因此我希望它们不受任何属性的影响,或者取决于某个框架。

我看了一下Json.NET中的自定义转换器,但是对我来说它们看起来非常“古老”,因为现在我们有了泛型,并且实现流利接口也不是很难。因此,在我走向弱类型等方面之前...

...我正在寻找的东西(伪代码):

public class MyModel {
    public int Id { get; set; }
    public string Name { get; set; }
    public SomeObj SomeObj { get; set; }
}

public class MyModelConverter : JsonConverter<MyModel> {

    public JsonConverter() {
        RuleFor(x => x.Id).Name("Identifier");
        RuleFor(x => x.SomeObj).Name("Data")
            .WithConverter(new SomeObjConverter());
        RuleFor(x => x.Name).Ignore();
    }

}

在Json.NET中有类似的东西吗?难道我错过了什么吗?(顺便说一句,由于这些模型是基于第三方规范的,所以我不能为我的属性等使用不同的名称)。


2
也许可以使用 AutoMapper 将领域对象映射到所需的类中?它的语法非常接近您要寻找的内容。 - code4life
1
扩展方法并发布自己的增强插件以支持JSON.NET! :-) - VulgarBinary
你可以简单地创建一个新的匿名类型,然后对其进行序列化。 ... new { Identifier = x.Id, ...} - Ian Mercer
2个回答

5
这里是我对如何实现所需API的看法:
根据评论进行了编辑。
public abstract class Rule
{
    private Dictionary<string, object> rule { get; } = new Dictionary<string, object>();

    protected void AddRule(string key, object value)
    {
        if (rule.ContainsKey(key))
        {
            rule.Add(key, value);
        }
        else
        {
            rule[key] = value;
        }
    }

    protected IEnumerable<KeyValuePair<string, object>> RegisteredRules
    {
        get
        {
            return rule.AsEnumerable();
        }
    }
}

public abstract class PropertyRule : Rule
{
    public MemberInfo PropertyInfo { get; protected set; }

    public void Update(JsonProperty contract)
    {
        var props = typeof(JsonProperty).GetProperties();
        foreach (var rule in RegisteredRules)
        {
            var property = props.Where(x => x.Name == rule.Key).FirstOrDefault();
            if (property != null)
            {
                var value = rule.Value;
                if (property.PropertyType == value.GetType())
                {
                    property.SetValue(contract, value);
                }
            }
        }
    }
}

public class PropertyRule<TClass, TProp> : PropertyRule
{
    public const string CONVERTER_KEY = "Converter";
    public const string PROPERTY_NAME_KEY = "PropertyName";
    public const string IGNORED_KEY = "Ignored";

    public PropertyRule(Expression<Func<TClass, TProp>> prop)
    {
        PropertyInfo = (prop.Body as System.Linq.Expressions.MemberExpression).Member;
    }

    public PropertyRule<TClass, TProp> Converter(JsonConverter converter)
    {
        AddRule(CONVERTER_KEY, converter);
        return this;
    }

    public PropertyRule<TClass, TProp> Name(string propertyName)
    {
        AddRule(PROPERTY_NAME_KEY, propertyName);
        return this;
    }

    public PropertyRule<TClass, TProp> Ignore()
    {
        AddRule(IGNORED_KEY, true);
        return this;
    }
}

public interface SerializationSettings
{
    IEnumerable<Rule> Rules { get; }
}

public class SerializationSettings<T> : SerializationSettings
{
    private List<Rule> rules { get; } = new List<Rule>();

    public IEnumerable<Rule> Rules { get; private set; }

    public SerializationSettings()
    {
        Rules = rules.AsEnumerable();
    }

    public PropertyRule<T, TProp> RuleFor<TProp>(Expression<Func<T, TProp>> prop)
    {
        var rule = new PropertyRule<T, TProp>(prop);
        rules.Add(rule);
        return rule;
    }
}

public class FluentContractResolver : DefaultContractResolver
{
    static List<SerializationSettings> settings;

    public static void SearchAssemblies(params Assembly[] assemblies)
    {
        SearchAssemblies((IEnumerable<Assembly>)assemblies);
    }

    public static void SearchAssemblies(IEnumerable<Assembly> assemblies)
    {
        settings = assemblies.SelectMany(x => x.GetTypes()).Where(t => IsSubclassOfRawGeneric(t, typeof(SerializationSettings<>))).Select(t => (SerializationSettings)Activator.CreateInstance(t)).ToList();
    }

    //https://dev59.com/vnRB5IYBdhLWcg3w9Lvn
    static bool IsSubclassOfRawGeneric(System.Type toCheck, System.Type generic)
    {
        if (toCheck != generic)
        {
            while (toCheck != null && toCheck != typeof(object))
            {
                var cur = toCheck.GetTypeInfo().IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
                if (generic == cur)
                {
                    return true;
                }
                toCheck = toCheck.GetTypeInfo().BaseType;
            }
        }
        return false;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var contract = base.CreateProperty(member, memberSerialization);

        var rule = settings.Where(x => x.GetType().GetTypeInfo().BaseType.GenericTypeArguments[0] == member.DeclaringType).SelectMany(x => x.Rules.Select(r => r as PropertyRule).Where(r => r != null && r.PropertyInfo.Name == member.Name)).FirstOrDefault();
        if (rule != null)
        {
            rule.Update(contract);
        }
        return contract;
    }
}

现在,在程序启动的某个地方:

FluentContractResolver.SearchAssemblies(typeof(MyModel).GetTypeInfo().Assembly);

Newtonsoft.Json.JsonConvert.DefaultSettings = () => 
{
    return new Newtonsoft.Json.JsonSerializerSettings
    {
        Formatting = Newtonsoft.Json.Formatting.Indented,
        ContractResolver = new FluentContractResolver()
    };
};

在这个基础上,您现在只需要使用流畅的设置添加类:

public class MyModelSettings : SerializationSettings<MyModel> 
{

    public MyModelSettings() 
    {
        RuleFor(x => x.Id).Name("Identifier");
        RuleFor(x => x.SomeObj).Name("Data").Converter(new SomeObjConverter());
        RuleFor(x => x.Name).Ignore();
    }

}

  1. PropertyRule.Update 中的第一行应该是: var props = typeof(JsonProperty).GetProperties();
  2. 对于 .NET Core,Type 属性 IsGenericType、Assembly 和 BaseType 可通过 GetTypeInfo() 访问。 除此之外,其他都没问题。很好的解决方案。
- Alexander Christov
@AlexanderChristov 我已根据您的评论编辑了代码。谢谢! - Nripendra

2

Fluent-Json.NET可以让你映射对象,使用类型识别器,而不会干扰你的数据对象。不需要任何属性。

映射类

public class AnimalMap : JsonMap<Animal>
{
    public AnimalMap()
    {
        this.DiscriminateSubClassesOnField("class");
        this.Map(x => x.Speed, "speed");
    }
}

public class FelineMap : JsonSubclassMap<Feline>
{
    public FelineMap()
    {
        this.Map(x => x.SightRange, "sight");
    }
}

public class LionMap : JsonSubclassMap<Lion>
{
    public LionMap()
    {
        this.DiscriminatorValue("lion");
        this.Map(x => x.Strength, "strength");
    }
}

模型类

public class Animal
{
    public Animal(float speed)
    {
        this.Speed = speed;
    }

    public float Speed { get; set; }
}

public abstract class Feline : Animal
{
    protected Feline(float speed, float sightRange) : base(speed)
    {
        this.SightRange = sightRange;
    }

    public float SightRange { get; set; }
}

public class Lion : Feline
{
    public Lion(float speed, float sightRange, float strength) : base(speed, sightRange)
    {
        this.Strength = strength;
    }

    public float Strength { get; set; }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接