add anyOf support (#7801)

This commit is contained in:
William Cheng
2020-10-27 17:02:05 +08:00
committed by GitHub
parent 5d27799bad
commit 042fc81f31
7 changed files with 516 additions and 110 deletions

View File

@@ -78,9 +78,10 @@ namespace {{packageName}}.Client
/// <summary>
/// Gets the Headers for HttpSigning
/// </summary>
/// <param name="method"></param>
/// <param name="path"></param>
/// <param name="requestOptions"></param>
/// <param name="basePath">Base path</param>
/// <param name="method">HTTP method</param>
/// <param name="path">Path</param>
/// <param name="requestOptions">Request options</param>
/// <returns></returns>
internal Dictionary<string, string> GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions)
{

View File

@@ -33,10 +33,15 @@ using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils;
using System.Reflection;
{{/-first}}
{{/oneOf}}
{{#aneOf}}
{{#-first}}
using System.Reflection;
{{/-first}}
{{/aneOf}}
namespace {{packageName}}.{{modelPackage}}
{
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{^oneOf}}{{>modelGeneric}}{{/oneOf}}{{/isEnum}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}}
{{/model}}
{{/models}}
}

View File

@@ -0,0 +1,218 @@
/// <summary>
/// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
/// </summary>
[JsonConverter(typeof({{classname}}JsonConverter))]
[DataContract(Name = "{{{name}}}")]
{{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}}
{
{{#isNullable}}
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}" /> class.
/// </summary>
public {{classname}}()
{
this.IsNullable = true;
this.SchemaType= "anyOf";
}
{{/isNullable}}
{{#anyOf}}
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}" /> class
/// with the <see cref="{{{.}}}" /> class
/// </summary>
/// <param name="actualInstance">An instance of {{{.}}}.</param>
public {{classname}}({{{.}}} actualInstance)
{
this.IsNullable = {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}};
this.SchemaType= "anyOf";
this.ActualInstance = actualInstance{{^isNullable}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isNullable}};
}
{{/anyOf}}
private Object _actualInstance;
/// <summary>
/// Gets or Sets ActualInstance
/// </summary>
public override Object ActualInstance
{
get
{
return _actualInstance;
}
set
{
{{#anyOf}}
{{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}}))
{
this._actualInstance = value;
}
{{/anyOf}}
else
{
throw new ArgumentException("Invalid instance found. Must be the following types:{{#anyOf}} {{{.}}}{{^-last}},{{/-last}}{{/anyOf}}");
}
}
}
{{#anyOf}}
/// <summary>
/// Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`,
/// the InvalidClassException will be thrown
/// </summary>
/// <returns>An instance of {{{.}}}</returns>
public {{{.}}} Get{{{.}}}()
{
return ({{{.}}})this.ActualInstance;
}
{{/anyOf}}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class {{classname}} {\n");
sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public override string ToJson()
{
return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings);
}
/// <summary>
/// Converts the JSON string into an instance of {{classname}}
/// </summary>
/// <param name="jsonString">JSON string</param>
/// <returns>An instance of {{classname}}</returns>
public static {{classname}} FromJson(string jsonString)
{
{{classname}} new{{classname}} = null;
{{#anyOf}}
try
{
new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings));
// deserialization is considered successful at this point if no exception has been thrown.
return new{{classname}};
}
catch (Exception exception)
{
// deserialization failed, try the next one
System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString()));
}
{{/anyOf}}
// no match found, throw an exception
throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined.");
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
{{#useCompareNetObjects}}
return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual;
{{/useCompareNetObjects}}
{{^useCompareNetObjects}}
return this.Equals(input as {{classname}});
{{/useCompareNetObjects}}
}
/// <summary>
/// Returns true if {{classname}} instances are equal
/// </summary>
/// <param name="input">Instance of {{classname}} to be compared</param>
/// <returns>Boolean</returns>
public bool Equals({{classname}} input)
{
{{#useCompareNetObjects}}
return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual;
{{/useCompareNetObjects}}
{{^useCompareNetObjects}}
if (input == null)
return false;
return this.ActualInstance.Equals(input.ActualInstance);
{{/useCompareNetObjects}}
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.ActualInstance != null)
hashCode = hashCode * 59 + this.ActualInstance.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
/// <summary>
/// Custom JSON converter for {{classname}}
/// </summary>
public class {{classname}}JsonConverter : JsonConverter
{
/// <summary>
/// To write the JSON string
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="value">Object to be converted into a JSON string</param>
/// <param name="serializer">JSON Serializer</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRaw((String)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null)));
}
/// <summary>
/// To convert a JSON string into an object
/// </summary>
/// <param name="reader">JSON reader</param>
/// <param name="objectType">Object type</param>
/// <param name="existingValue">Existing value</param>
/// <param name="serializer">JSON Serializer</param>
/// <returns>The object converted from the JSON string</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None));
}
/// <summary>
/// Check if the object can be converted
/// </summary>
/// <param name="objectType">Object type</param>
/// <returns>True if the object can be converted</returns>
public override bool CanConvert(Type objectType)
{
return false;
}
}

View File

@@ -78,9 +78,10 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Gets the Headers for HttpSigning
/// </summary>
/// <param name="method"></param>
/// <param name="path"></param>
/// <param name="requestOptions"></param>
/// <param name="basePath">Base path</param>
/// <param name="method">HTTP method</param>
/// <param name="path">Path</param>
/// <param name="requestOptions">Request options</param>
/// <returns></returns>
internal Dictionary<string, string> GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions)
{

View File

@@ -29,47 +29,82 @@ namespace Org.OpenAPITools.Model
/// <summary>
/// GmFruit
/// </summary>
[JsonConverter(typeof(GmFruitJsonConverter))]
[DataContract(Name = "gmFruit")]
public partial class GmFruit : IEquatable<GmFruit>, IValidatableObject
public partial class GmFruit : AbstractOpenAPISchema, IEquatable<GmFruit>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GmFruit" /> class.
/// Initializes a new instance of the <see cref="GmFruit" /> class
/// with the <see cref="Apple" /> class
/// </summary>
/// <param name="color">color.</param>
/// <param name="cultivar">cultivar.</param>
/// <param name="origin">origin.</param>
/// <param name="lengthCm">lengthCm.</param>
public GmFruit(string color = default(string), string cultivar = default(string), string origin = default(string), decimal lengthCm = default(decimal))
/// <param name="actualInstance">An instance of Apple.</param>
public GmFruit(Apple actualInstance)
{
this.Color = color;
this.Cultivar = cultivar;
this.Origin = origin;
this.LengthCm = lengthCm;
this.IsNullable = false;
this.SchemaType= "anyOf";
this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null.");
}
/// <summary>
/// Gets or Sets Color
/// Initializes a new instance of the <see cref="GmFruit" /> class
/// with the <see cref="Banana" /> class
/// </summary>
[DataMember(Name = "color", EmitDefaultValue = false)]
public string Color { get; set; }
/// <param name="actualInstance">An instance of Banana.</param>
public GmFruit(Banana actualInstance)
{
this.IsNullable = false;
this.SchemaType= "anyOf";
this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null.");
}
private Object _actualInstance;
/// <summary>
/// Gets or Sets Cultivar
/// Gets or Sets ActualInstance
/// </summary>
[DataMember(Name = "cultivar", EmitDefaultValue = false)]
public string Cultivar { get; set; }
public override Object ActualInstance
{
get
{
return _actualInstance;
}
set
{
if (value.GetType() == typeof(Apple))
{
this._actualInstance = value;
}
else if (value.GetType() == typeof(Banana))
{
this._actualInstance = value;
}
else
{
throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana");
}
}
}
/// <summary>
/// Gets or Sets Origin
/// Get the actual instance of `Apple`. If the actual instanct is not `Apple`,
/// the InvalidClassException will be thrown
/// </summary>
[DataMember(Name = "origin", EmitDefaultValue = false)]
public string Origin { get; set; }
/// <returns>An instance of Apple</returns>
public Apple GetApple()
{
return (Apple)this.ActualInstance;
}
/// <summary>
/// Gets or Sets LengthCm
/// Get the actual instance of `Banana`. If the actual instanct is not `Banana`,
/// the InvalidClassException will be thrown
/// </summary>
[DataMember(Name = "lengthCm", EmitDefaultValue = false)]
public decimal LengthCm { get; set; }
/// <returns>An instance of Banana</returns>
public Banana GetBanana()
{
return (Banana)this.ActualInstance;
}
/// <summary>
/// Returns the string presentation of the object
@@ -79,10 +114,7 @@ namespace Org.OpenAPITools.Model
{
var sb = new StringBuilder();
sb.Append("class GmFruit {\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Cultivar: ").Append(Cultivar).Append("\n");
sb.Append(" Origin: ").Append(Origin).Append("\n");
sb.Append(" LengthCm: ").Append(LengthCm).Append("\n");
sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
@@ -91,9 +123,46 @@ namespace Org.OpenAPITools.Model
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
public override string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
return JsonConvert.SerializeObject(this.ActualInstance, GmFruit.SerializerSettings);
}
/// <summary>
/// Converts the JSON string into an instance of GmFruit
/// </summary>
/// <param name="jsonString">JSON string</param>
/// <returns>An instance of GmFruit</returns>
public static GmFruit FromJson(string jsonString)
{
GmFruit newGmFruit = null;
try
{
newGmFruit = new GmFruit(JsonConvert.DeserializeObject<Apple>(jsonString, GmFruit.SerializerSettings));
// deserialization is considered successful at this point if no exception has been thrown.
return newGmFruit;
}
catch (Exception exception)
{
// deserialization failed, try the next one
System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString()));
}
try
{
newGmFruit = new GmFruit(JsonConvert.DeserializeObject<Banana>(jsonString, GmFruit.SerializerSettings));
// deserialization is considered successful at this point if no exception has been thrown.
return newGmFruit;
}
catch (Exception exception)
{
// deserialization failed, try the next one
System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString()));
}
// no match found, throw an exception
throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined.");
}
/// <summary>
@@ -125,13 +194,8 @@ namespace Org.OpenAPITools.Model
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Color != null)
hashCode = hashCode * 59 + this.Color.GetHashCode();
if (this.Cultivar != null)
hashCode = hashCode * 59 + this.Cultivar.GetHashCode();
if (this.Origin != null)
hashCode = hashCode * 59 + this.Origin.GetHashCode();
hashCode = hashCode * 59 + this.LengthCm.GetHashCode();
if (this.ActualInstance != null)
hashCode = hashCode * 59 + this.ActualInstance.GetHashCode();
return hashCode;
}
}
@@ -143,22 +207,48 @@ namespace Org.OpenAPITools.Model
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Cultivar (string) pattern
Regex regexCultivar = new Regex(@"^[a-zA-Z\\s]*$", RegexOptions.CultureInvariant);
if (false == regexCultivar.Match(this.Cultivar).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" });
}
// Origin (string) pattern
Regex regexOrigin = new Regex(@"^[A-Z\\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (false == regexOrigin.Match(this.Origin).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" });
}
yield break;
}
}
/// <summary>
/// Custom JSON converter for GmFruit
/// </summary>
public class GmFruitJsonConverter : JsonConverter
{
/// <summary>
/// To write the JSON string
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="value">Object to be converted into a JSON string</param>
/// <param name="serializer">JSON Serializer</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRaw((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null)));
}
/// <summary>
/// To convert a JSON string into an object
/// </summary>
/// <param name="reader">JSON reader</param>
/// <param name="objectType">Object type</param>
/// <param name="existingValue">Existing value</param>
/// <param name="serializer">JSON Serializer</param>
/// <returns>The object converted from the JSON string</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return GmFruit.FromJson(JObject.Load(reader).ToString(Formatting.None));
}
/// <summary>
/// Check if the object can be converted
/// </summary>
/// <param name="objectType">Object type</param>
/// <returns>True if the object can be converted</returns>
public override bool CanConvert(Type objectType)
{
return false;
}
}
}

View File

@@ -78,9 +78,10 @@ namespace Org.OpenAPITools.Client
/// <summary>
/// Gets the Headers for HttpSigning
/// </summary>
/// <param name="method"></param>
/// <param name="path"></param>
/// <param name="requestOptions"></param>
/// <param name="basePath">Base path</param>
/// <param name="method">HTTP method</param>
/// <param name="path">Path</param>
/// <param name="requestOptions">Request options</param>
/// <returns></returns>
internal Dictionary<string, string> GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions)
{

View File

@@ -29,47 +29,82 @@ namespace Org.OpenAPITools.Model
/// <summary>
/// GmFruit
/// </summary>
[JsonConverter(typeof(GmFruitJsonConverter))]
[DataContract(Name = "gmFruit")]
public partial class GmFruit : IEquatable<GmFruit>, IValidatableObject
public partial class GmFruit : AbstractOpenAPISchema, IEquatable<GmFruit>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GmFruit" /> class.
/// Initializes a new instance of the <see cref="GmFruit" /> class
/// with the <see cref="Apple" /> class
/// </summary>
/// <param name="color">color.</param>
/// <param name="cultivar">cultivar.</param>
/// <param name="origin">origin.</param>
/// <param name="lengthCm">lengthCm.</param>
public GmFruit(string color = default(string), string cultivar = default(string), string origin = default(string), decimal lengthCm = default(decimal))
/// <param name="actualInstance">An instance of Apple.</param>
public GmFruit(Apple actualInstance)
{
this.Color = color;
this.Cultivar = cultivar;
this.Origin = origin;
this.LengthCm = lengthCm;
this.IsNullable = false;
this.SchemaType= "anyOf";
this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null.");
}
/// <summary>
/// Gets or Sets Color
/// Initializes a new instance of the <see cref="GmFruit" /> class
/// with the <see cref="Banana" /> class
/// </summary>
[DataMember(Name = "color", EmitDefaultValue = false)]
public string Color { get; set; }
/// <param name="actualInstance">An instance of Banana.</param>
public GmFruit(Banana actualInstance)
{
this.IsNullable = false;
this.SchemaType= "anyOf";
this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null.");
}
private Object _actualInstance;
/// <summary>
/// Gets or Sets Cultivar
/// Gets or Sets ActualInstance
/// </summary>
[DataMember(Name = "cultivar", EmitDefaultValue = false)]
public string Cultivar { get; set; }
public override Object ActualInstance
{
get
{
return _actualInstance;
}
set
{
if (value.GetType() == typeof(Apple))
{
this._actualInstance = value;
}
else if (value.GetType() == typeof(Banana))
{
this._actualInstance = value;
}
else
{
throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana");
}
}
}
/// <summary>
/// Gets or Sets Origin
/// Get the actual instance of `Apple`. If the actual instanct is not `Apple`,
/// the InvalidClassException will be thrown
/// </summary>
[DataMember(Name = "origin", EmitDefaultValue = false)]
public string Origin { get; set; }
/// <returns>An instance of Apple</returns>
public Apple GetApple()
{
return (Apple)this.ActualInstance;
}
/// <summary>
/// Gets or Sets LengthCm
/// Get the actual instance of `Banana`. If the actual instanct is not `Banana`,
/// the InvalidClassException will be thrown
/// </summary>
[DataMember(Name = "lengthCm", EmitDefaultValue = false)]
public decimal LengthCm { get; set; }
/// <returns>An instance of Banana</returns>
public Banana GetBanana()
{
return (Banana)this.ActualInstance;
}
/// <summary>
/// Returns the string presentation of the object
@@ -79,10 +114,7 @@ namespace Org.OpenAPITools.Model
{
var sb = new StringBuilder();
sb.Append("class GmFruit {\n");
sb.Append(" Color: ").Append(Color).Append("\n");
sb.Append(" Cultivar: ").Append(Cultivar).Append("\n");
sb.Append(" Origin: ").Append(Origin).Append("\n");
sb.Append(" LengthCm: ").Append(LengthCm).Append("\n");
sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
@@ -91,9 +123,46 @@ namespace Org.OpenAPITools.Model
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
public override string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
return JsonConvert.SerializeObject(this.ActualInstance, GmFruit.SerializerSettings);
}
/// <summary>
/// Converts the JSON string into an instance of GmFruit
/// </summary>
/// <param name="jsonString">JSON string</param>
/// <returns>An instance of GmFruit</returns>
public static GmFruit FromJson(string jsonString)
{
GmFruit newGmFruit = null;
try
{
newGmFruit = new GmFruit(JsonConvert.DeserializeObject<Apple>(jsonString, GmFruit.SerializerSettings));
// deserialization is considered successful at this point if no exception has been thrown.
return newGmFruit;
}
catch (Exception exception)
{
// deserialization failed, try the next one
System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString()));
}
try
{
newGmFruit = new GmFruit(JsonConvert.DeserializeObject<Banana>(jsonString, GmFruit.SerializerSettings));
// deserialization is considered successful at this point if no exception has been thrown.
return newGmFruit;
}
catch (Exception exception)
{
// deserialization failed, try the next one
System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString()));
}
// no match found, throw an exception
throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined.");
}
/// <summary>
@@ -125,13 +194,8 @@ namespace Org.OpenAPITools.Model
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Color != null)
hashCode = hashCode * 59 + this.Color.GetHashCode();
if (this.Cultivar != null)
hashCode = hashCode * 59 + this.Cultivar.GetHashCode();
if (this.Origin != null)
hashCode = hashCode * 59 + this.Origin.GetHashCode();
hashCode = hashCode * 59 + this.LengthCm.GetHashCode();
if (this.ActualInstance != null)
hashCode = hashCode * 59 + this.ActualInstance.GetHashCode();
return hashCode;
}
}
@@ -143,22 +207,48 @@ namespace Org.OpenAPITools.Model
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Cultivar (string) pattern
Regex regexCultivar = new Regex(@"^[a-zA-Z\\s]*$", RegexOptions.CultureInvariant);
if (false == regexCultivar.Match(this.Cultivar).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" });
}
// Origin (string) pattern
Regex regexOrigin = new Regex(@"^[A-Z\\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (false == regexOrigin.Match(this.Origin).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" });
}
yield break;
}
}
/// <summary>
/// Custom JSON converter for GmFruit
/// </summary>
public class GmFruitJsonConverter : JsonConverter
{
/// <summary>
/// To write the JSON string
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="value">Object to be converted into a JSON string</param>
/// <param name="serializer">JSON Serializer</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRaw((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null)));
}
/// <summary>
/// To convert a JSON string into an object
/// </summary>
/// <param name="reader">JSON reader</param>
/// <param name="objectType">Object type</param>
/// <param name="existingValue">Existing value</param>
/// <param name="serializer">JSON Serializer</param>
/// <returns>The object converted from the JSON string</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return GmFruit.FromJson(JObject.Load(reader).ToString(Formatting.None));
}
/// <summary>
/// Check if the object can be converted
/// </summary>
/// <param name="objectType">Object type</param>
/// <returns>True if the object can be converted</returns>
public override bool CanConvert(Type objectType)
{
return false;
}
}
}