问题
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