JSON.NET Deserialization Property Name conversion to ExpandoObject with custom ContractResolver

只愿长相守 提交于 2019-12-06 07:19:52

问题


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?


回答1:


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("_",""); 
    }
}


来源:https://stackoverflow.com/questions/20526805/json-net-deserialization-property-name-conversion-to-expandoobject-with-custom-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!