Is there a way to ignore get-only properties in Json.NET without using JsonIgnore attributes?

后端 未结 4 1209
不知归路
不知归路 2020-11-29 05:19

Is there a way to ignore get-only properties using the Json.NET serializer but without using JsonIgnore attributes?

For example, I have a class with the

4条回答
  •  不知归路
    2020-11-29 05:29

    Use the OptIn mode of JSON.net and you'll only need to decorate the properties you want to serialize. This isn't as good as automatically opting out all read only properties, but it can save you some work.

    [JsonObject(MemberSerialization.OptIn)]
    public class MyClass
    {
        [JsonProperty]
        public string serializedProp { get; set; }
    
        public string nonSerializedProp { get; set; }
    }
    

    Udate: Added another possibility using reflection

    If the above solution still isn't quite what you're looking for, you could use reflection to make dictionary objects which would then be serialized. Of course the example below will only work for simple classes, so you would need to add recursion if your classes contain other classes. This should at least point you in the right direction.

    The subroutine to put the filtered result into a dictionary:

        private Dictionary ConvertToDictionary(object classToSerialize)
        {
            Dictionary resultDictionary = new Dictionary();
    
            foreach (var propertyInfo in classToSerialize.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (propertyInfo.CanWrite) resultDictionary.Add(propertyInfo.Name, propertyInfo.GetValue(classToSerialize, null));
            }
    
            return resultDictionary;
        }
    

    A snippet showing its use:

    SampleClass sampleClass = new SampleClass();
    sampleClass.Hotkey = Keys.A;
    var toSerialize = ConvertToDictionary(sampleClass);
    String resultText = JsonConvert.SerializeObject(toSerialize);
    

提交回复
热议问题