如何将类元数据转换为 JSON 字符串

本文关键字:JSON 字符串 转换 元数据 | 更新日期: 2023-09-27 18:33:18

如何生成类元数据的JSON。

例如。

C# 类

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public Description Description { get; set; }
}
public class Description
{
    public string Content { get; set; }
    public string ShortContent { get; set; }
}

杰伦

[
    {
        "PropertyName" : "Id",
        "Type" : "Int",
        "IsPrimitive" : true
    },
    {
        "PropertyName" : "Name",
        "Type" : "string",
        "IsPrimitive" : true
    },
    {
        "PropertyName" : "IsActive",
        "Type" : "bool",
        "IsPrimitive" : true
    },
    {
        "PropertyName" : "Description",
        "Type" : "Description",
        "IsPrimitive" : false
        "Properties" : {
            {
                "PropertyName" : "Content",
                "Type" : "string",
                "IsPrimitive" : true
            },
            {
                "PropertyName" : "ShortContent",
                "Type" : "string",
                "IsPrimitive" : true
            }
        }
    },
]

如何将类元数据转换为 JSON 字符串

如果定义将映射 Json 模型的类:

public class PropertyDescription
{
    public string PropertyName { get; set; }
    public string Type { get; set; }
    public bool IsPrimitive { get; set; }
    public IEnumerable<PropertyDescription> Properties { get; set; }
}

然后只需创建一个以递归方式读取对象属性的函数:

public static List<PropertyDescription> ReadObject(Type type)
{
    var propertyDescriptions = new List<PropertyDescription>();
    foreach (var propertyInfo in type.GetProperties())
    {
        var propertyDescription = new PropertyDescription
        {
            PropertyName = propertyInfo.Name,
            Type = propertyInfo.PropertyType.Name
        };
        if (!propertyDescription.IsPrimitive
            // String is not a primitive type
            && propertyInfo.PropertyType != typeof (string))
        {
            propertyDescription.IsPrimitive = false;
            propertyDescription.Properties = ReadObject(propertyInfo.PropertyType);
        }
        else
        {
            propertyDescription.IsPrimitive = true;            
        }
        propertyDescriptions.Add(propertyDescription);
    }
    return propertyDescriptions;
}

您可以使用 Json.Net 来序列化此函数的结果:

var result = ReadObject(typeof(Product));
var json = JsonConvert.SerializeObject(result);

编辑:基于@AmitKumarGhosh答案的Linq解决方案:

public static IEnumerable<object> ReadType(Type type)
{
    return type.GetProperties().Select(a => new
    {
        PropertyName = a.Name,
        Type = a.PropertyType.Name,
        IsPrimitive = a.PropertyType.IsPrimitive && a.PropertyType != typeof (string),
        Properties = (a.PropertyType.IsPrimitive && a.PropertyType != typeof(string)) ? null : ReadType(a.PropertyType)
    }).ToList();
}
...
var result = ReadType(typeof(Product));
json = JsonConvert.SerializeObject(result);

一个可能的解决方案 -

static void Main(string[] args)
    {
        var o = typeof(Product).GetProperties().Select(a =>
            {
                if (a.PropertyType != null && (a.PropertyType.IsPrimitive || a.PropertyType == typeof(string)))
                {
                    return MapType(a);
                }
                else
                {
                    dynamic p = null;
                    var t = MapType(a);
                    var props = a.PropertyType.GetProperties();
                    if (props != null)
                    { p = new { t, Properties = props.Select(MapType).ToList() }; }
                    return new { p.t.PropertyName, p.t.Type, p.t.IsPrimitive, p.Properties };
                }
            }).ToList();
        var jsonString = JsonConvert.SerializeObject(o);
    }
    static dynamic MapType(PropertyInfo a)
    {
        return new
        {
            PropertyName = a.Name,
            Type = a.PropertyType.Name,
            IsPrimitive = a.PropertyType != null && a.PropertyType.IsPrimitive
        };
    }

试试这个,概念是从对象到字典获取所有元素。字段名称和值。对于每个属性,在字典中创建其他元素(使用反射),如Type,IsPrimitive等。您可以使用递归来抛出属性,然后将此字典序列化为 JSON。

这里有一个例子:

使用 JSON.net 追加到 JSON 对象

这方面的一个例子:

        var serialize = new Newtonsoft.Json.JsonSerializer();
        var dict = GetDic(new Description());
        serialize.Serialize(sr, dict);

和 GetDcit 实现:

    private List<Dictionary<string, string>> GetDic(object obj)
    {
        var result= new List<Dictionary<string, string>>();
        foreach (var r in obj.GetType().GetProperties())
        {
            result.Add(new Dictionary<string, string>
            {
                ["PropertyName"] = r.Name,
                ["Type"] = r.PropertyType.Name,
                ["IsPrimitive"] = r.GetType().IsPrimitive.ToString(),
            });
        }
        return result;
    }