How to get Class Metadata into JSON string

妖精的绣舞 提交于 2021-02-07 08:39:56

问题


How to generate JSON of Class meta data.

for eg.

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
            }
        }
    },
]

回答1:


If you define a class that will map your Json Model:

public class PropertyDescription
{
    public string PropertyName { get; set; }

    public string Type { get; set; }

    public bool IsPrimitive { get; set; }

    public IEnumerable<PropertyDescription> Properties { get; set; }
}

And then just create a function that read the properties of your object recursively:

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

You can use Json.Net to serialize the result of this function :

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

EDIT: Linq solution based on @AmitKumarGhosh answer:

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



回答2:


One probable solution -

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



回答3:


Try this, concept is get all elements from object to dictionary. Field name and value. For each property create additional elements (using Reflection) in dictionary like Type, IsPrimitive etc. You can use recursion for going throw properties and then serialize this dictionary to JSON.

An example here:

Appending to JSON object using JSON.net

An example of this:

        var serialize = new Newtonsoft.Json.JsonSerializer();

        var dict = GetDic(new Description());

        serialize.Serialize(sr, dict);

And GetDcit implementation:

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


来源:https://stackoverflow.com/questions/35222366/how-to-get-class-metadata-into-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!