C# |从具有值的静态 class 字段创建一个 json 字符串

C# | Create a json string out of static class fields with values

我需要一种方法能够遍历 static 属性 中的每个 static class ],然后将它们组合成一个字符串,使用 json 语法 ,其中键名等于 属性 名称,键值将是 [= 的值45=].

因此结果将是一个字符串,其值为:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }

我有一个工作方法成功地完成了相反的工作 - 采用 json 并将数据映射到静态字段。但不知道如何反过来做

    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .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;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }

示例静态 class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }

p.s。 保存在字符串中的键值对,可以像

一样在末尾换行
    ResultString = "{ " + resultString + " }";

C# .NET 4.7.2(控制台应用程序)

正如其他人所说,static class 在这里不是一个好的设计。

但是,可以通过一些简单的反射将其映射回 JSON:

public static JObject MapStaticClassToJson(Type staticClassToMap)
{
    var result = new JObject();
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    {
        result.Add(new JProperty(prop.Name, prop.GetValue(null, null)));
    }
    
    return result;
}

我认为如果有一些简单的代码也可以将 json 属性分配给静态 class 属性会很好。我使用@RichardDeeming answer

创建了这段代码
public static void MapStaticClassFromJson(string json, Type staticClassToMap)
{
    var jsonObject = JObject.Parse(json);
        
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    prop.SetValue(null, Convert.ChangeType(jsonObject[prop.Name], prop.PropertyType, CultureInfo.CurrentCulture), null);
}

测试

 MapStaticClassFromJson(json,typeof(Data));
 Console.WriteLine(Data.StaticPropertyName_int); 
 Console.WriteLine(Data.StaticPropertyName_string);

结果

34
string_value_of_this_property