我有这样的JSON:
{名字:约翰,姓氏:李四}这JSON.NET合同解析器:
公共类CustomContractResolver:DefaultContractResolver {保护覆盖字符串ResolvePropertyName(字符串propertyName的) {返回propertyName.Replace(_,); } }和我有这样的WebAPI控制器的方法,采用一个的expando使用提供的字段分贝行的部分更新:
公共虚拟INT邮报(INT ID,JObject内容) { VAR OBJ = JsonConvert.DeserializeObject< ExpandoObject>(content.ToString(),新JsonSerializerSettings {ContractResolver =新CustomContractResolver()}); db.Update<人>(ID,OBJ)}
我预计反序列化的expando有属性 FIRST_NAME 和姓氏,以配合我的模型/ DB列名,而是它的性能仍然匹配JSON。直接反序列化到人的 FIRST_NAME 和姓氏的作品,如磅帮我发现下面,但我的DB层希望在Expando局部记录更新,否则它会吹走的所有属性的人未由JSON,因此规定空在模型中。
我可以在ContractResolver做的属性转换为在Expando?
解决方案您可以使用此ContractResolver而反序列化
VAR OBJ = JsonConvert.DeserializeObject<&人GT;( JSON,新JsonSerializerSettings { ContractResolver =新CustomContractResolver()});公开类CustomContractResolver:Newtonsoft.Json.Serialization.DefaultContractResolver {保护覆盖字符串ResolvePropertyName(字符串propertyName的) {返回propertyName.Replace(_,); } }
I have this JSON:
{"firstName": "John","lastName": "Doe"}This JSON.NET Contract Resolver:
public class CustomContractResolver : DefaultContractResolver{ protected override string ResolvePropertyName(string propertyName) { return propertyName.Replace("_",""); } }And I have this WebApi Controller method with uses an expando to a partial update of a db row using the provided fields:
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) }I expect the deserialized expando to have properties first_name and last_name to match my model/db column names, but instead its properties still match the JSON. Deserializing directly to Person has first_name and last_name works, as L.B. helped me discover below, but my db layer wants an Expando for partial record updates, otherwise it'll blow away any properties of the Person that are not specified by the json and therefore null in the Model.
What can I do in the ContractResolver to convert the properties for an Expando?
解决方案You can use this ContractResolver while deserialization
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("_",""); } }
更多推荐
JSON.NET反序列化属性名称转换为自定义ExpandoObject ContractResolver
发布评论