gpt4 book ai didi

c# - C#中将json文件反序列化为静态类

转载 作者:行者123 更新时间:2023-12-02 03:35:33 27 4
gpt4 key购买 nike

我有一个带有静态字段和 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));
}
}

关于c# - C#中将json文件反序列化为静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50340801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com