Добрый день!
Достался в наследство проект, активно использующий эту библиотеку, и вот уже который день ломаю голову над такой проблемой: JsonConvert.SerializeObject почему то пропускает одно Integer поле в объекте. Их того что уже проверил: [JsonIgnore] не используется, в ContractResolver тоже ничего криминального нет. В общем идеи кончились. Может кто-нибудь что то подскажет?
Код класса:
<System.Diagnostics.DebuggerStepThroughAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0"), _
System.Runtime.Serialization.DataContractAttribute(Name:="Document", [Namespace]:="http://schemas.datacontract.org/2004/07/Greenway.PrimeSuite.DataContracts.Documen"& _
"t")> _
Partial Public Class Document
Inherits Object
Implements System.Runtime.Serialization.IExtensibleDataObject
Private extensionDataField As System.Runtime.Serialization.ExtensionDataObject
Private DocumentIdField As Integer
Private DocumentIdSpecifiedField As Boolean
Private SequenceNumberField As Integer
Public Property ExtensionData() As System.Runtime.Serialization.ExtensionDataObject Implements System.Runtime.Serialization.IExtensibleDataObject.ExtensionData
Get
Return Me.extensionDataField
End Get
Set
Me.extensionDataField = value
End Set
End Property
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Property DocumentId() As Integer
Get
Return Me.DocumentIdField
End Get
Set
Me.DocumentIdField = value
End Set
End Property
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Property DocumentIdSpecified() As Boolean
Get
Return Me.DocumentIdSpecifiedField
End Get
Set
Me.DocumentIdSpecifiedField = value
End Set
End Property
<System.Runtime.Serialization.DataMemberAttribute()> _
Public Property SequenceNumber() As Integer
Get
Return Me.SequenceNumberField
End Get
Set
Me.SequenceNumberField = value
End Set
End Property
End Class
Код сериализации:
private static string GetJsonExample(object instance, Type body)
{
var settings = new JsonSerializerSettings { ContractResolver = new SpecialContractResolver() };
return JsonConvert.SerializeObject(instance, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { ContractResolver = new SpecialContractResolver() }); //
}
SpecialContractResolver:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Runtime.Serialization;
namespace Greenway.Services.API.Rest.Docs
{
public class SpecialContractResolver : DefaultContractResolver
{
protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
{
if (member.MemberType == MemberTypes.Property)
{
var pi = (PropertyInfo)member;
if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return new NullableValueProvider(member, pi.PropertyType.GetGenericArguments().First());
}
else if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(pi.PropertyType);
return new NullableValueProvider(member, pi.PropertyType);
}
else if (pi.PropertyType.IsClass && member.Name != "ExtensionData" && !pi.PropertyType.IsPrimitive && !pi.PropertyType.IsValueType && pi.PropertyType != typeof(String))
{
return new NullableValueProvider(member, pi.PropertyType);
}
else if (pi.PropertyType.Name == "String")
{
return new NullableValueProvider(member, pi.PropertyType);
}
}
else if (member.MemberType == MemberTypes.Field)
{
var fi = (FieldInfo)member;
if (fi.FieldType.IsGenericType && fi.FieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
return new NullableValueProvider(member, fi.FieldType.GetGenericArguments().First());
}
return base.CreateMemberValueProvider(member);
}
}
public class NullableValueProvider : IValueProvider
{
private readonly object _defaultValue;
private readonly object _defaultValue1;
private readonly IValueProvider _underlyingValueProvider;
public NullableValueProvider(MemberInfo memberInfo, Type underlyingType)
{
var pi = (PropertyInfo)memberInfo;
_underlyingValueProvider = new DynamicValueProvider(memberInfo);
if (pi.PropertyType.Name == "String")
_defaultValue = "String Content";
else if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
_defaultValue1 = Activator.CreateInstance(pi.PropertyType.GetGenericArguments().First());
Type myObject = _defaultValue1.GetType();
var IListRef = typeof(List<>);
Type[] IListParam = { myObject };
_defaultValue = Activator.CreateInstance(IListRef.MakeGenericType(IListParam));
_defaultValue.GetType().GetMethod("Add").Invoke(_defaultValue, new[] { _defaultValue1 });
}
else if (underlyingType.IsArray)
{
Array _defaultValue2 = Array.CreateInstance(underlyingType.GetElementType(), 1);
var tmp = Activator.CreateInstance(underlyingType.GetElementType());
_defaultValue2.SetValue(tmp, 0);
_defaultValue = _defaultValue2;
}
else
{
_defaultValue = Activator.CreateInstance(underlyingType);
var temp = "";
}
}
public void SetValue(object target, object value)
{
_underlyingValueProvider.SetValue(target, value);
}
public object GetValue(object target)
{
if (_underlyingValueProvider.GetValue(target) != null)
{
return _underlyingValueProvider.GetValue(target);
}
else
{
return _defaultValue;
}
}
}
}