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

时间:2016-02-05 10:56:18

标签: c# .net json

如何生成类元数据的JSON。

例如。

C#Classes

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

JSON

[
    {
        "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
            }
        }
    },
]

3 个答案:

答案 0 :(得分:4)

如果你定义一个将映射你的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);

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

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

答案 1 :(得分:3)

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

这里有一个例子:

Appending to JSON object using JSON.net

这方面的一个例子:

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

答案 2 :(得分:3)

一个可能的解决方案 -

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
        };
    }
相关问题