[英]Deserializing a json file into a static class in C#
我有一個帶有靜態字段和json的靜態類。
我可以將json反序列化為動態對象,因此我擁有所有字段,並且它們與類中的靜態字段完全匹配。
如何使用反射枚舉字段並將值從動態類復制到靜態類字段?
我無法更改體系結構,使其成為單例,等等; 它是共享代碼,並且該類將保持靜態,因為它是共享庫使用的全局共享設置對象。
該解決方案需要使用反射,因為該類隨着新成員的發展而發展。 否則,我可能已經編寫了一個自定義解串器。
添加更多細節,但實際上沒有太多:
我有這個靜態類:
static class A
{
static int I;
static string S;
}
和一個與字段完全匹配的json:
{
"I" : 3,
"S" : "hello"
}
var Data = JsonConvert.Deserialize<dynamic>(...);
我想使用從json反序列化的值將A類的靜態字段初始化為動態對象。
另一個編輯:
我想出了與David所寫內容相似的內容,但是效率較低,因為我使用反序列化器來轉換類型,因此David的解決方案更好。
這是我想出的:
foreach (var Destination in typeof(Settings).GetProperties())
{
var Name = Destination.Name;
var T = Destination.PropertyType;
var Value = JsonConvert.DeserializeObject("\"" + JT[Name] + "\"", T);
Destination.SetValue(null, Value);
}
通過具有匹配的非靜態類,獲取源和目標的屬性並遍歷每個類,可以非常輕松地實現此目的。 例如,假設我們有兩個類:
public static class A
{
public static int I { get; set; }
public static string S { get; set; }
}
public class B
{
public int I { get; set; }
public string S { get; set; }
}
我們現在可以這樣做:
public void MapToStaticClass(B source)
{
var sourceProperties = source.GetType().GetProperties();
//Key thing here is to specify we want the static properties only
var destinationProperties = typeof(A)
.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (var prop in sourceProperties)
{
//Find matching property by name
var destinationProp = destinationProperties
.Single(p => p.Name == prop.Name);
//Set the static property value
destinationProp.SetValue(null, prop.GetValue(source));
}
}
另一個選擇是反序列化到JToken
並將其與反射結合使用:
var source = JsonConvert.DeserializeObject<JToken>(json);
接着:
public void MapJTokenToStaticClass(JToken source)
{
var destinationProperties = typeof(A)
.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (JProperty prop in source)
{
var destinationProp = destinationProperties
.SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
var value = ((JValue)prop.Value).Value;
//The ChangeType is required because JSON.Net will deserialise
//numbers as long by default
destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.