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

标签 c# json .net json.net

我需要一个能够循环遍历静态类中的每个静态属性的方法,并使用json语法将它们组合成一个字符串 strong>,其中键名称等于属性名称,键值将是属性的值。

所以结果将是一个带有值的字符串:

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

静态类示例:

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

附: 键值对保存在字符串中,可以像这样包裹在末尾

    ResultString = "{ " + resultString + " }";

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

最佳答案

正如其他人所说,静态类在这里并不是一个好的设计。

但是,可以通过一些简单的反射将其映射回 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;
}

关于C# |从带有值的静态类字段创建一个 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71083724/

相关文章:

c# - 从 vb asp 到 C# asp .net 的转换

c# - Azure Data Lake 中的 U-SQL 查询错误

c# - 反序列化数组内的数组

javascript - 从 JSON 数组中获取数据

c# - 如何为我的应用程序添加可编程性

c# - C++ 等效于 C# Yield?

c# - EventToCommand 无法添加到 TriggerActionCollection

c# - PostSharp 给出 MissingMethodException

.NET Bootstrap 无需设置

.net - 编写可切换到 Web 的桌面程序