JSON.NET反序列化属性名称转换为具有自定义ContractResolver的ExpandoObject

时间:2013-12-11 18:12:05

标签: c# json asp.net-web-api json.net deserialization

我有这个JSON:

{"firstName": "John","lastName": "Doe"}

这个JSON.NET合同解析器:

public class CustomContractResolver : DefaultContractResolver{      
  protected override string ResolvePropertyName(string propertyName)
  {
    return propertyName.Replace("_",""); 
  }
}

我有这个WebApi Controller方法,使用expando来使用提供的字段部分更新db行:

public virtual int Post(int id, JObject content)
{
  var obj = JsonConvert.DeserializeObject<ExpandoObject>(content.ToString(), new JsonSerializerSettings { ContractResolver = new CustomContractResolver() });
  db.Update<Person>(id, obj)
}

我希望反序列化的expando具有属性first_namelast_name来匹配我的模型/ db列名,但是它的属性仍然匹配JSON。直接反序列化为Person first_namelast_name的作用,如L.B.帮助我发现下面,但我的数据库层需要一个Expando来进行部分记录更新,否则它会吹掉Person的任何未被json指定的属性,因此模型中的null

我可以在ContractResolver中做什么来转换Expando的属性?

1 个答案:

答案 0 :(得分:4)

您可以在反序列化时使用此ContractResolver

var obj = JsonConvert.DeserializeObject<Person>(
            json, 
            new JsonSerializerSettings { 
                    ContractResolver = new CustomContractResolver() 
            });

public class CustomContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    protected override string ResolvePropertyName(string propertyName)
    {
        return propertyName.Replace("_",""); 
    }
}