.NET NewtonSoft JSON deserialize map to a different property name

后端 未结 5 658
情歌与酒
情歌与酒 2020-11-22 09:20

I have following JSON string which is received from an external party.

{
   \"team\":[
      {
         \"v1\":\"\",
         \"attributes\":{
            \"         


        
5条回答
  •  隐瞒了意图╮
    2020-11-22 09:43

    If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me

    Usage:

    var settings = new JsonSerializerSettings();
    settings.DateFormatString = "YYYY-MM-DD";
    settings.ContractResolver = new CustomContractResolver();
    this.DataContext = JsonConvert.DeserializeObject(jsonString, settings);
    

    Logic:

    public class CustomContractResolver : DefaultContractResolver
    {
        private Dictionary PropertyMappings { get; set; }
    
        public CustomContractResolver()
        {
            this.PropertyMappings = new Dictionary 
            {
                {"Meta", "meta"},
                {"LastUpdated", "last_updated"},
                {"Disclaimer", "disclaimer"},
                {"License", "license"},
                {"CountResults", "results"},
                {"Term", "term"},
                {"Count", "count"},
            };
        }
    
        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }
    

提交回复
热议问题