Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

.net - Can Json.NET populate readonly fields in a class?

I haven't seen much information about Json.NET supporting deserializing objects with readonly fields. I do notice that the .NET DataContract and DataMember attributes allow for populating readonly fields during deserializtion, but Json.NET doesn't seem to support this, at least from the behavior I'm seeing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not the most elegant solution, but you can extend the DefaultConstractResolver to do it:

public class ContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        property.Writable = CanSetMemberValue(member, true);
        return property;
    }

    public static bool CanSetMemberValue(MemberInfo member, bool nonPublic)
    {
        switch (member.MemberType)
        {
            case MemberTypes.Field:
                var fieldInfo = (FieldInfo)member;

                return nonPublic || fieldInfo.IsPublic;
            case MemberTypes.Property:
                var propertyInfo = (PropertyInfo)member;

                if (!propertyInfo.CanWrite)
                    return false;
                if (nonPublic)
                    return true;
                return (propertyInfo.GetSetMethod(nonPublic) != null);
            default:
                return false;
        }
    }
}

I have just remove one little check from the CanSetMemberValue method. Unfortunately it's neither virtual nor an instance method, so I had to override CreateProperty as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...