[英]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.