Use JSON.NET to generate JSON schema with extra attributes

后端 未结 5 2098
鱼传尺愫
鱼传尺愫 2020-12-28 08:28

I am using JSON.NET to generate JSON Schema from c# object class. But I was unable to add any other json schema attributes e.g. maxLength, pattern(regex to validate email),

5条回答
  •  生来不讨喜
    2020-12-28 08:32

    You could use the JavaScriptSerializer class.Like:

    namespace ExtensionMethods
    {
        public static class JSONHelper
        {
            public static string ToJSON(this object obj)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Serialize(obj);
            }
    
            public static string ToJSON(this object obj, int recursionDepth)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                serializer.RecursionLimit = recursionDepth;
                return serializer.Serialize(obj);
            }
        }
    }
    

    Use it like this:

    using ExtensionMethods;
    
    ...
    
    List people = new List{
                       new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                       new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
                       };
    
    
    string jsonString = people.ToJSON();
    

    Read also this articles:

    1. http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
    2. http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
    3. http://www.asp.net/AJAX/Documentation/Live/mref/T_System_Web_Script_Serialization_JavaScriptSerializer.aspx

    You can also try ServiceStack JsonSerializer

    One example to use it:

     var customer = new Customer { Name="Joe Bloggs", Age=31 };
        var json = JsonSerializer.SerializeToString(customer);
        var fromJson = JsonSerializer.DeserializeFromString(json); 
    

提交回复
热议问题