2012-04-23 73 views
15

我使用JSON.NET從c#對象類生成JSON模式。但是我無法添加任何其他json模式屬性,例如(正則表達式來驗證電子郵件)等使用JSON.NET生成具有額外屬性的JSON模式

以下是我的工作代碼,我只能生成具有所需屬性的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" 
      ] 
     } 
    } 
} 

回答

-4

你可以使用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); 
     } 
    } 
} 

使用方法如下:

using ExtensionMethods; 

... 

List<Person> people = new List<Person>{ 
        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<Customer>(json); 
+2

我不太看到這是如何解決的問題。 – unomi 2013-05-27 04:30:16

0

您可以創建類似這樣的自定義JsonConverter。我用反射來填寫屬性。

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

這很有用,但我不認爲我會將'JsonConverter'屬性添加到類中,因爲那麼當需要使用實際數據(而不是模式)序列化類時,它將不起作用。相反,在創建模式時將轉換器的實例傳遞給'SerializeObject'方法。 – 2014-01-09 19:34:02

-4
  • 第一轉換你到XML
  • 現在添加您想添加和成JSON XML轉換XML節點JSON文件。

這種轉換可以通過'newtonsoft.json.jsonconvert'類輕鬆完成。要使用此類,只需在項目中導入newtonsoft.json dll。

+0

這是一個壞主意。根本不需要使用XML來創建JSON模式。此外,根據具體情況,結構信息有時會在從JSON來回轉換爲XML時丟失。 – 2014-01-09 19:30:06

7

Json.NET Schema現在已經大大改進了對模式生成的支持。

您可以使用.NET的Data Annotation屬性註釋屬性,以在模式上指定諸如minimum,maximum,minLength,maxLength等的信息。

還有JSchemaGenerationProvider,可讓您在爲類型生成模式時進行完全控制。

更多細節在這裏:http://www.newtonsoft.com/jsonschema/help/html/GeneratingSchemas.htm

+1

您可以幫助我們提及他們在商業用途許可中提及的內容嗎?我們仍然可以將其作爲免費產品使用嗎? http://www.newtonsoft.com/jsonschema#licensing – Rikki 2015-09-28 09:44:41

+0

json-schema對商業用途沒有用處。你必須從他們那裏購買許可證。我認爲你最好使用麻省理工學院的NJsonSchema:https://github.com/RSuter/NJsonSchema – juFo 2017-11-29 09:48:31

7

詹姆斯·牛頓 - 景乃權在his answer,我只是一個代碼示例展開它讓人們跌跌撞撞到這個網頁上並不需要研究整個documentation

因此,您可以使用.NET提供的屬性來指定這些附加選項,例如字符串的最大長度或允許的正則表達式模式。以下是一些示例:

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模式,您需要使用JSchemaGenerator類與分佈的Json.NET架構包。如果您使用較舊的JsonSchemaGenerator,則需要進行一些升級,因爲它現在已被棄用,並且不包含上述的新功能。

下面是生成JSON模式爲上述類別的樣本函數:

/// <summary> 
    /// Generates JSON schema for a given C# class using Newtonsoft.Json.Schema library. 
    /// </summary> 
    /// <param name="myType">class type</param> 
    /// <returns>a string containing JSON schema for a given class type</returns> 
    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));