3

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
            }
        }
    },
]
3
  • So you don't want the value, just the description of the type ? Commented Feb 5, 2016 at 11:18
  • @Thomas No, i just need a member info of class so that i can pass it to the consumer Commented Feb 5, 2016 at 11:27
  • see my post, this should do what you want. Commented Feb 5, 2016 at 11:28

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Excellent solution! But instead of passing object i wanna pass Type to the ReadObject function. like ReadObject(Product.GetType())
I've edited my answer to pass the type instead of the value. Can you mark the question as answer if it's ok for you ?
Works fine. Thank you so much :)
I'm pretty sure that this won't work with DateTime or Nullable Primitives
If you can confirm that it does not work, please feel free to edit my answer or post an another answer
3

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

1 Comment

this is working as of this hierarchy and provides a possible solution.
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;
    } 

2 Comments

Why writing the Json in a file ?
For no reason. It is only copy paste from my project. I update my answer. Thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.