[英]How to add all class properties along with the values to Hashable in C#?
I have below 2 model classes:我有以下 2 个 model 类:
public class InitiateRequest
{
/// <summary>
///
/// </summary>
public string FormCode { get; set; }
/// <summary>
///
/// </summary>
public InitiateFormField Fields { get; set; }
}
public class InitiateFormField
{
[Required]
[JsonPropertyName("STD_INCIDENTTYPEID")]
public string IncidentTypeId { get; set; }
[Required]
public string STD_SUBJECTTYPEID { get; set; }
[Required]
public string STD_SUBJECTID { get; set; }
public string STD_PARENTSUBJECTID { get; set; }
public int PREPARER_ID { get; set; }
public string EXISTING_FORMER_CLIENT { get; set; }
public string MATTER_TITLE { get; set; }
public string MATTER_DESCRIPTION { get; set; }
public int SUBMITTING_ATTORNEY { get; set; }
public int NEW_MATTER_RESPONSIBLE_ATTORNEY { get; set; }
public string MATTER_TYPE { get; set; }
public string MATTER_PRACTICE_CODE { get; set; }
public string NEW_CLIENT_CODE { get; set; }
}
I want to add all the properties from InitiateFormField
class to a Hashtable.我想将
InitiateFormField
class 中的所有属性添加到哈希表中。 var properties = new Hashtable();
Hashtable Key is the name of the model property and value is the actual value of the property. Hashtable Key 是 model 属性的名称, value 是属性的实际值。
Eg例如
properties.Add("STD_INCIDENTTYPEID", "myString");
Is there a way to do this?有没有办法做到这一点?
I do not understand why one should use HashTable
instead of a Dictionary, but I'm digressing.我不明白为什么应该使用
HashTable
而不是 Dictionary,但我离题了。
Given your code, I assume you have access to Json.NET.给定您的代码,我假设您可以访问 Json.NET。
You can convert any Json object to a Dictionary<string, object>
, so you can:您可以将任何 Json object 转换为
Dictionary<string, object>
,因此您可以:
var serializedFields = JsonConvert.SerializeObject(request.Fields);
var fieldsDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>();
// if you _really_ need a hashTable:
var hashTable = new HashTable(fieldsDictionary);
There are possibly more efficient ways, but given the optimization of Json.NET and the fact that you are guaranteed to use only serializable types, I think this is the simplest solution.可能有更有效的方法,但考虑到 Json.NET 的优化以及保证您只使用可序列化类型的事实,我认为这是最简单的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.