I have a json that has field names with '_'. However, the class where I need to map these fields doesn't have underscore. As the field names doesn't match I get the values for the mapped class as null. I want to remove the underscore from the json fields before mapping them to the entity class. Can you please suggest which way it can be done - using CustomConverter or using DefaultContractResolver and which one be a better implementation. example json like :
{\"My_UnitOfStudyStatus_Code\":\"1234\"
And corresponding entity class has a field called MyUnitOfStudyStatusCode I need a generic solution that I can use for all my json and for mapping to all corresponding entities.
I was trying to desterilize as below
JsonConvert.DeserializeObject<TEntityType>(jsonString, new IgnoreUnderScoreConverter<TEntityType>()
Where for the converter implementation I was trying and stuck at below :
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
JObject jobject = JObject.Load(reader);
var model = new T();
//Need to rename fields for jobject
serializer.Populate(renamed.CreateReader(), model);
return model;
}
But I might be missing here something that I can't rename the fields that I get from jobject before they gets mapped to the entity class. Please suggest.
You can use the JsonPropertyName attribute. eg:
[JsonPropertyName("_name")]
public string Name {get;set;}
this will deserialize correctly even though the property name in json has a underscore in it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With