C# 已解析的JSON.NET协定不应用于内部对象
我正在尝试使用JSON.NET反序列化一个复杂的JSON结构,例如:C# 已解析的JSON.NET协定不应用于内部对象,c#,json.net,C#,Json.net,我正在尝试使用JSON.NET反序列化一个复杂的JSON结构,例如: { "a": 1, "b": "value", "c": { "d": "hello" } } 我需要对c属性应用值转换器 我使用的是合同解析程序,如下所示: public class CustomPropertyResolver : DefaultContractResolver { protected override IList<JsonProperty> CreatePro
{
"a": 1,
"b": "value",
"c": {
"d": "hello"
}
}
我需要对c
属性应用值转换器
我使用的是合同解析程序,如下所示:
public class CustomPropertyResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in props.Where(p => p.PropertyType == typeof(string)))
{
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null && pi.GetCustomAttribute(typeof(MyCustomAttribute), true) != null)
{
prop.ValueProvider = new MyStringValueProvider(pi);
}
}
return props;
}
您的
ReverseValueProvider.SetValue()
方法未被调用的原因是,您的类型ClassA
和ClassB
是使用参数化构造函数构造的,传入的值是要反转的值:
public class ClassB
{
public ClassB(string c)
{
// You would like c to be reversed but it's not since it's never set via its setter.
this.C = c;
}
[Reverse]
[JsonProperty("c")]
public string C { get; set; }
}
因为Json.NET是通过构造函数填充这些值的,所以它从不调用相应的属性设置器,字符串也从不反转
为确保调用setter(从而反转字符串),可以向类型中添加私有无参数构造函数,并使用以下标记:
我已经添加了复制。当对象被序列化时,您添加的MCVE正确地反转了所有值(和嵌套值)。您是否希望反序列化时执行
ReverseValueProvider
?是的,应该打印“hello”和“world”
public class ClassB
{
public ClassB(string c)
{
// You would like c to be reversed but it's not since it's never set via its setter.
this.C = c;
}
[Reverse]
[JsonProperty("c")]
public string C { get; set; }
}
public class ClassA
{
[JsonConstructor]
ClassA() {}
public ClassA(string a, ClassB b)
{
this.A = a;
this.B = b;
}
[Reverse]
[JsonProperty("a")]
public string A { get; set; }
[JsonProperty("b")]
public ClassB B { get; set; }
}
public class ClassB
{
[JsonConstructor]
ClassB() { }
public ClassB(string c)
{
this.C = c;
}
[Reverse]
[JsonProperty("c")]
public string C { get; set; }
}