使用JSON.NET生成具有额外属性的JSON模式

我正在使用JSON.NET从c#对象类生成JSON Schema。 但是我无法添加任何其他json架构属性,例如maxLength,pattern(用于validation电子邮件的正则表达式)等

下面是我的工作代码,我只能生成带有必需属性的json模式。 如果有人能发布一些关于如何为json模式添加额外属性的代码示例,那将是很棒的。

谢谢,

我的代码示例

public class Customer { [JsonProperty(Required = Required.Always)] public int CustomerID { get; set; } [JsonProperty(Required = Required.Always)] public string FirstName { get; set; } [JsonProperty(Required = Required.Always)] public string LastName { get; set; } [JsonProperty(Required = Required.Always)] public string Email { get; set; } [JsonProperty(Required = Required.AllowNull)] public string Phone { get; set; } } 

 { "title" : "Customer", "type" : "object", "properties" : { "CustomerID" : { "required" : true, "type" : "integer" }, "FirstName" : { "required" : true, "type" : "string" }, "LastName" : { "required" : true, "type" : "string" }, "Email" : { "required" : true, "type" : "string" }, "Phone" : { "required" : true, "type" : [ "string", "null" ] } } } 

James Newton-King在他的回答中是正确的,我只是用代码示例扩展它,所以人们绊倒在这个页面上不需要研究整个文档 。

因此,您可以使用.NET提供的属性来指定那些addidional选项,例如字符串的最大长度或允许的正则表达式模式。 这里有些例子:

 public class MyDataModel { public enum SampleEnum { EnumPosition1, EnumPosition2, EnumPosition3 } [JsonProperty(Required = Required.Always)] [RegularExpression(@"^[0-9]+$")] public string PatternTest { get; set; } [JsonProperty(Required = Required.Always)] [MaxLength(3)] public string MaxLength3 { get; set; } [JsonProperty(Required = Required.AllowNull)] [EnumDataType(typeof(SampleEnum))] public string EnumProperty { get; set; } } 

上面的注释来自System.ComponentModel.DataAnnotations命名空间。

要使这些附加属性影响生成的json模式,您需要使用随Json.NET Schema包一起分发的JSchemaGenerator类。 如果您使用较旧的JsonSchemaGenerator ,则需要进行一些升级,因为它现已弃用,并且不包含上述新function。

这是一个为上面的类生成Json Schema的示例函数:

  ///  /// Generates JSON schema for a given C# class using Newtonsoft.Json.Schema library. ///  /// class type /// a string containing JSON schema for a given class type internal static string GenerateSchemaForClass(Type myType) { JSchemaGenerator jsonSchemaGenerator = new JSchemaGenerator(); JSchema schema = jsonSchemaGenerator.Generate(myType); schema.Title = myType.Name; return schema.ToString(); } 

你可以像这样使用它:

  string schema = GenerateSchemaForClass(typeof(MyDataModel)); 

Json.NET Schema现在有了很多改进的模式生成支持。

您可以使用.NET的Data Annotation属性注释属性,以指定模式上的minimum,maximum,minLength,maxLength等信息。

还有JSchemaGenerationProvider,可以在为类型生成模式时完全控制。

更多细节: http : //www.newtonsoft.com/jsonschema/help/html/GeneratingSchemas.htm

您可以创建这样的自定义JsonConverter。 我用reflection来填充属性。

  public class UserConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var user = (User)value; var result = new StringBuilder("{"); result.Append("title : " + user.GetType().Name + ", "); result.Append("properties : {"); foreach (var prop in user.GetType().GetProperties()) { result.Append(prop.Name + ": {"); result.Append("value : " + Convert.ToString(prop.GetValue(user, null)) + ", "); var attribute = (JsonPropertyAttribute)Attribute.GetCustomAttributes(prop)[0]; if (attribute.Required == Required.Always) result.Append("required : true, "); result.Append("type : " + prop.PropertyType.Name.ToLower()); result.Append(" }"); } writer.WriteValue(result.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var user = new User { UserName = (string)reader.Value }; return user; } public override bool CanConvert(Type objectType) { return objectType == typeof(User); } } 

 [JsonConverter(typeof(UserConverter))] public class User { [JsonProperty(Required = Required.Always)] public string UserName { get; set; } } //Run string json = JsonConvert.SerializeObject(manager, Formatting.Indented); Console.WriteLine(json); 

你可以使用JavaScriptSerializer类。喜欢:

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

像这样用它:

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

另请阅读本文:

  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

您也可以尝试ServiceStack JsonSerializer

使用它的一个例子:

  var customer = new Customer { Name="Joe Bloggs", Age=31 }; var json = JsonSerializer.SerializeToString(customer); var fromJson = JsonSerializer.DeserializeFromString(json); 
  • 首先将json文件转换为xml
  • 现在添加要添加的xml节点并将xml转换为json。

这种转换可以通过’newtonsoft.json.jsonconvert’类轻松完成。 要使用此类,只需在项目中导入newtonsoft.json dll。