简体   繁体   English

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

[英]Deserializing a json file into a static class in C#

I have a static class with static fields and a json. 我有一个带有静态字段和json的静态类。

I can deserialize the json into a dynamic object, so I have all the fields and they match exactly the static fields in the class. 我可以将json反序列化为动态对象,因此我拥有所有字段,并且它们与类中的静态字段完全匹配。

How can I use reflection to enumerate the fields and copy the values from the dynamic class into the static class fields? 如何使用反射枚举字段并将值从动态类复制到静态类字段?

I can't change the architecture, make it a singleton, etc; 我无法更改体系结构,使其成为单例,等等; it's shared code and the class is going to remain static since it's globally shared settings object used by a shared library. 它是共享代码,并且该类将保持静态,因为它是共享库使用的全局共享设置对象。

The solution needs to use reflection since the class evolves over time with new members. 该解决方案需要使用反射,因为该类随着新成员的发展而发展。 Otherwise I could have written a custom deserializer. 否则,我可能已经编写了一个自定义解串器。


Adding more details, but there is really not much: 添加更多细节,但实际上没有太多:

I have this static class: 我有这个静态类:

static class A
{
    static int I;
    static string S;
}

and a json matching the fields exactly: 和一个与字段完全匹配的json:

{
    "I" : 3,
    "S" : "hello"
}

var Data = JsonConvert.Deserialize<dynamic>(...);

I would like to initialize the static fields of class A with the values I deserialized from the json, into a dynamic object. 我想使用从json反序列化的值将A类的静态字段初始化为动态对象。


Another edit: 另一个编辑:

I came up with something similar to what David wrote, but this is less efficient since I use the deserializer to convert types, so David's solution is better. 我想出了与David所写内容相似的内容,但是效率较低,因为我使用反序列化器来转换类型,因此David的解决方案更好。

here's what I came up with: 这是我想出的:

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);
}

You can do this quite easily by having a matching non-static class, getting the properties of source and destination and looping through each one. 通过具有匹配的非静态类,获取源和目标的属性并遍历每个类,可以非常轻松地实现此目的。 For example, assuming we have two classes: 例如,假设我们有两个类:

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; }
}

We can now do this: 我们现在可以这样做:

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));
    }
}

Another option is to deserialise to JToken and use that combined with reflection: 另一个选择是反序列化到JToken并将其与反射结合使用:

var source = JsonConvert.DeserializeObject<JToken>(json);

And then: 接着:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM