Accessing value of JsonPropertyAttribute in C# [duplicate]

大兔子大兔子 提交于 2019-12-11 15:01:40

问题


Am having a class of this nature,

using Newtonsoft.Json;

namespace Models
{
    public class ItemsDbTable
    {
          [JsonProperty("City")]
          public string City { get; set; }
          [JsonProperty("Delivery.no")]
          public string DeliveryNo { get; set; }
          [JsonProperty("Delivery.type")]
          public string DeliveryType { get; set; }
          [JsonProperty("House.street.no")]
          public string HouseStreetNo { get; set; }
    }
}

Now the interesting part is when i have a List of ItemsDbTable and i start to iterate it. I want to get the values of the iterated instance of ItemsDbTable using the JsonPropertyAttribute.

Here is what i was doing,

Because my data came in via a web app, i Json-ised it but the fields are different than the ones i have for my Model. Thats why i used a JsonPropertyAttribute to aid in the mapping. But then am using another source of data which still refers to the old names that Json has to get the values.

Let me show you what am talking about.

 var itemsDbRow = str.ItemsDbTable.Single(x => 
     x.ArticlesKey == itemsTable.ArticlesKey);

So here i have an instance of itemsDbTable class.

Then i have a variable that is coming from somewhere, it however has the JsonPropertyAttributeName.

Then i search for the value like this

var val = itemsDbRow.GetType().GetProperties()
     .Select(propertyInfo => propertyInfo.GetCustomAttributesData()
     .Where(x => x.ConstructorArguments[0].Value.ToString() == bindingValueSrc));

来源:https://stackoverflow.com/questions/53982500/accessing-value-of-jsonpropertyattribute-in-c-sharp

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