示例#1
0
        public static void OverrideReadOnAttribute()
        {
            JsonSerializerOptions      options = new JsonSerializerOptions();
            JsonPropertyValueAttribute attr    = new JsonPropertyValueAttribute();

            attr.IgnoreNullValueOnRead = true;
            options.AddAttribute(typeof(TestClassWithNullButInitialized), attr);

            TestClassWithNullButInitialized obj = JsonSerializer.Parse <TestClassWithNullButInitialized>(TestClassWithNullButInitialized.s_json, options);

            Assert.Equal("Hello", obj.MyString);
            Assert.Equal(1, obj.MyInt);
        }
示例#2
0
        public static void OverrideWriteOnAttribute()
        {
            JsonSerializerOptions      options = new JsonSerializerOptions();
            JsonPropertyValueAttribute attr    = new JsonPropertyValueAttribute();

            attr.IgnoreNullValueOnWrite = true;
            options.AddAttribute(typeof(TestClassWithNull), attr);

            var    input = new TestClassWithNull();
            string json  = JsonSerializer.ToString(input, options);

            Assert.Equal(@"{}", json);
        }
示例#3
0
        public static TValue GetPropertyClassAssemblyPolicy <TValue>(
            Type parentClassType,
            PropertyInfo propertyInfo,
            JsonSerializerOptions options,
            Func <JsonPropertyValueAttribute, TValue> selector)
        {
            TValue value;

            JsonPropertyValueAttribute attr = null;

            if (propertyInfo != null)
            {
                // Use Property first
                attr = options.GetAttributes <JsonPropertyValueAttribute>(propertyInfo).FirstOrDefault();
            }

            if (attr == null || (value = selector(attr)) == default)
            {
                // Then class type
                attr = options.GetAttributes <JsonPropertyValueAttribute>(parentClassType, inherit: true).FirstOrDefault();
                if (attr == null || (value = selector(attr)) == default)
                {
                    // Then declaring assembly
                    attr = options.GetAttributes <JsonPropertyValueAttribute>(parentClassType.Assembly).FirstOrDefault();

                    if (attr == null || (value = selector(attr)) == default)
                    {
                        // Then global
                        attr = options.GetAttributes <JsonPropertyValueAttribute>(JsonSerializerOptions.GlobalAttributesProvider).FirstOrDefault();

                        if (attr == null)
                        {
                            value = default;
                        }
                        else
                        {
                            value = selector(attr);
                        }
                    }
                }
            }

            return(value);
        }