您可以使用 Json.NET 的 IContractResolver
为您的 Device
对象获取 JsonObjectContract
,其中包含有关该类型的所有属性的信息,包括它们的 JSON 名称和获取/设置方法。以下扩展方法可以解决问题:
public static partial class JsonExtensions
{
static readonly IContractResolver defaultResolver = JsonSerializer.CreateDefault().ContractResolver;
public static void SetJsonProperty<T>(T obj,string jsonName,object value,bool exact = false,IContractResolver resolver = null)
{
if (!TrySetJsonProperty(obj,jsonName,value,exact,resolver))
throw new ArgumentException(string.Format("Could not set property {0} in {1}.",obj));
}
public static bool TrySetJsonProperty<T>(T obj,IContractResolver resolver = null)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
resolver = resolver ?? defaultResolver;
var contract = resolver.ResolveContract(obj.GetType()) as JsonObjectContract;
if (contract == null)
return false;
var property = contract.Properties.GetProperty(jsonName,exact ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
if (property == null || !property.Writable)
return false;
property.ValueProvider.SetValue(obj,value);
return true;
}
}
此外,如果您正在读取文本文件并且您的某些属性值类型不是字符串,则需要将文件中的文本值转换为适当的 .Net 类型。以下是这样做的:
public static partial class JsonExtensions
{
public static void SetConvertibleJsonProperty<T,TConvertible>(T obj,TConvertible value,IContractResolver resolver = null) where TConvertible : IConvertible
{
if (!TrySetConvertibleJsonProperty(obj,obj));
}
public static bool TrySetConvertibleJsonProperty<T,exact ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
if (property == null || !property.Writable)
return false;
var finalValue = value == null ? null : Convert.ChangeType(value,Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType,CultureInfo.InvariantCulture);
property.ValueProvider.SetValue(obj,finalValue);
return true;
}
}
要使用它,请执行以下操作:
JsonExtensions.SetConvertibleJsonProperty(temp_obj,"ALLTYPES_NAME","Object1");
JsonExtensions.SetConvertibleJsonProperty(temp_obj,"Object2");
JsonExtensions.SetConvertibleJsonProperty(temp_obj,"INFORMATION","Inside_Information");
// The following sets the following property
// [JsonProperty("DECIMAL_DATA")]
// public decimal DecimalInformation { get; set; }
JsonExtensions.SetConvertibleJsonProperty(temp_obj,"DECIMAL_DATA","3.1111");
注意事项:
演示小提琴here。
,
经过一些实验,根据 Jon Skeet 的评论,我意识到我什至不需要为此使用 JSON 指令,正如您从以下代码摘录中看到的:
System.Reflection.PropertyInfo[] list_of_attributes =
(new Own_Class()).GetType().GetProperties();
string[] list_of_attribute_names = new string[list_of_attributes.Length];
for (int i = 0; i< list_of_attributes.Length; i++)
list_of_attribute_names[i] = list_of_attributes[i].Name;
combobox_on_form.Items.AddRange(list_of_attribute_names);
本文链接:https://www.f2er.com/35845.html