10

The JsonProperty class returned by DefaultContractResolver.CreateProperty has two properties about converter, Converter and MemberConverter. I don't find enough explanation about them, so what's the difference between them? When to use each one? What property to set in the contract resolver? "Gets or sets the member converter" from the official documentation isn't helpful.

4

2 回答 2

3

似乎 NS.Json 支持可覆盖的转换器;大概是这样,每个单独的属性都不必指定 JsonConverter,但如果需要,它们可能会覆盖它。

提示可以在源代码中找到:

DefaultContractResolver.cs,第 1254 行:

private void SetPropertySettingsFromAttributes(JsonProperty property, object attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess)
{
    ...
    // resolve converter for property
    // the class type might have a converter but the property converter takes presidence
    property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider);
    property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider);

JsonSerializerInternalReader.cs,第 348 行

    private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty)
    {
        JsonConverter converter = null;
        if (memberConverter != null)
        {
            // member attribute converter
            converter = memberConverter;
        }
        else if (containerProperty != null && containerProperty.ItemConverter != null)
        {
            converter = containerProperty.ItemConverter;
        }
        else if (containerContract != null && containerContract.ItemConverter != null)
        {
            converter = containerContract.ItemConverter;
        }
        else if (contract != null)
        {
            JsonConverter matchingConverter;
            if (contract.Converter != null)
                // class attribute converter
                converter = contract.Converter;
            else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null)
                // passed in converters
                converter = matchingConverter;
            else if (contract.InternalConverter != null)
                // internally specified converter
                converter = contract.InternalConverter;
        }
        return converter;
    }
于 2014-07-14T20:58:26.423 回答
2

我在这里github.com/JamesNK/Newtonsoft.Json/issues/363上打开了一个关于文档的问题。

但是它们之间的一个明显区别(从源代码中显而易见)是 Converter 仅在序列化时使用,而 MemberConverter 仅在反序列化时使用。我不知道这是否是完整的故事,而且命名并没有说明太多。

于 2014-09-04T12:53:09.033 回答