反序列化问题JsonProperty ContractResolver

时间:2016-03-08 20:11:48

标签: c# json json.net deserialization

我有自定义属性:

[JsonProperty("123abc")]
public int Id {get; set;}

var container = Serializer.Deserialize<ResponseContainer<T>>(new JsonTextReader(new StreamReader(stream)));

似乎我必须覆盖DefaultContractResolver,它是我继承的代码的一部分,它可能实际上没有处理自定义字段。

private readonly Dictionary<MemberInfo, string> _names = new Dictionary<MemberInfo, string>();

public ContractResolver() : base(false) { }

protected override string ResolvePropertyName(string propertyName)
{  return propertyName;     }

protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
   var lst = new List<JsonProperty>();
   foreach (var member in GetSerializableMembers(type))     {
          var prop = CreateProperty(member, memberSerialization);
                    string customName;
          **if (_names.TryGetValue(member, out customName))
                 prop.PropertyName = customName;**
          lst.Add(prop);
    }
    return lst;
}

&#34;突出显示的行&#34;不进行&#34;映射,&#34; Id始终为0.我查找了一些答案,并将代码更改为:

private Dictionary<string, string> PropertyMappings  = new Dictionary<string, string>{{"Id", "123abc"}  };   
protected override string ResolvePropertyName(string propertyName)
{
    string resolvedName = null;
    var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
    return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}

将null转换为int时出错。我可能错过了一些细节......请建议。谢谢!

0 个答案:

没有答案