本文整理汇总了C#中Newtonsoft.Json.Schema.JsonSchemaGenerator类的典型用法代码示例。如果您正苦于以下问题:C# JsonSchemaGenerator类的具体用法?C# JsonSchemaGenerator怎么用?C# JsonSchemaGenerator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonSchemaGenerator类属于Newtonsoft.Json.Schema命名空间,在下文中一共展示了JsonSchemaGenerator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateSchema
public static JsonSchema GenerateSchema(Type type)
{
var schemaGenerator = new JsonSchemaGenerator();
var schema = schemaGenerator.Generate(type);
schema.Title = type.Name;
return schema.MapSchemaTypes(type);
}
示例2: GenerateConfigSchema
/// <summary>
/// Generate JSON schema for redwood.json file.
/// </summary>
private static void GenerateConfigSchema(string outputFile)
{
var generator = new JsonSchemaGenerator();
var schema = generator.Generate(typeof(RedwoodConfiguration));
using (var textWriter = new StreamWriter(outputFile))
{
using (var writer = new JsonTextWriter(textWriter))
{
writer.Formatting = Formatting.Indented;
schema.WriteTo(writer);
}
}
}
示例3: OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parameterDescriptors = filterContext.ActionDescriptor.GetParameters();
//// Get json data
var rawValue = filterContext.Controller.ValueProvider.GetValue("data");
var rawData = string.Empty;
if (rawValue == null)
{
return;
}
else
{
rawData = rawValue.AttemptedValue;
}
//// Check Parameter type
if (parameterDescriptors.Count() != 1 || parameterDescriptors.First().ParameterType.IsValueType)
{
return;
}
//// Get json schema from parameter
JsonSchema jsonSchema = null;
var parameterDescriptor = parameterDescriptors.First();
var jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchema = jsonSchemaGenerator.Generate(parameterDescriptor.ParameterType);
jsonSchema.Title = parameterDescriptor.ParameterType.Name;
jsonSchema = JsonSchema.Parse(jsonSchema.ToString().ToLower());
var errs = new List<string>() as IList<string>;
JObject jsonObject = null;
//// 處理Json格式的異常
try
{
jsonObject = JObject.Parse(rawData.ToLower());
}
catch (JsonReaderException ex)
{
throw new JsonSchemaNotValidException(ex.Message, ex);
}
var valid = jsonObject.IsValid(jsonSchema, out errs);
if (errs.Count > 0)
{
throw new JsonSchemaNotValidException("請確認傳入資料型別是否符合規範!" +
string.Join(",", errs.ToArray()));
}
}
示例4: GetOrCreate
public TypeDefinition GetOrCreate(Type type)
{
TypeDefinition def;
if (_cache == null)
{
_generator = new JsonSchemaGenerator();
if (_supportRecursive) _generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
_cache = new Dictionary<Type, TypeDefinition>();
}
if (!_cache.TryGetValue(type, out def))
{
def = new TypeDefinition(type, _generator, this);
_cache.Add(type, def);
}
return def;
}
示例5: ReadAsInt32Failure
public void ReadAsInt32Failure()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 5 exceeds maximum value of 2. Line 1, position 1.",
() =>
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof(int));
s.Maximum = 2;
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5")))
{
Schema = s
};
reader.ReadAsInt32();
});
}
示例6: ReadAsInt32
public void ReadAsInt32()
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof (int));
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"1")))
{
Schema = s
};
int? i = reader.ReadAsInt32();
Assert.AreEqual(1, i);
}
示例7: ReadAsBytes
public void ReadAsBytes()
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof (byte[]));
byte[] data = Encoding.UTF8.GetBytes("Hello world");
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"""" + Convert.ToBase64String(data) + @"""")))
{
Schema = s
};
byte[] bytes = reader.ReadAsBytes();
CollectionAssert.AreEquivalent(data, bytes);
}
示例8: ReadAsDecimalFailure
public void ReadAsDecimalFailure()
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof (decimal));
s.DivisibleBy = 1;
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5")))
{
Schema = s
};
reader.ReadAsDecimal();
}
示例9: ReadAsInt32Failure
public void ReadAsInt32Failure()
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof (int));
s.Maximum = 2;
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5")))
{
Schema = s
};
reader.ReadAsInt32();
}
示例10: TypeDefinition
public TypeDefinition(Type type,JsonSchemaGenerator generator,TypeDefinitionContainer container)
{
_type = type;
_schema = generator.Generate(type, true);
_canNull = HasFlag(_schema.Type, JsonSchemaType.Null);
_isArray = HasFlag(_schema.Type, JsonSchemaType.Array);
_isObject = HasFlag(_schema.Type, JsonSchemaType.Object);
if (_isArray && _isObject)
throw new ApplicationException(string.Format("Type {0} is both array and object.", type.FullName));
if (_isArray)
{
_subType = GetCollectionItemType(_type);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
_subType = type.GetGenericArguments()[0];
var subDef = container.GetOrCreate(_subType);
_name = subDef.Name;
_demoValue = subDef.DemoValue;
}
else if (type == typeof(DateTime))
{
_name = "dateTime";
_demoValue = JsonConvert.SerializeObject(DateTime.Now).Trim('\"');
}
else if (type == typeof(byte[]))
{
_name = "base64binary";
_demoValue = JsonConvert.SerializeObject(Encoding.UTF8.GetBytes("Cus.WebApi")).Trim('\"');
}
_isLeaf = !(_isArray || _isObject);
_id = Guid.NewGuid().ToString("N");
if (_name == null)
{
if (IsArray)
{
_name = "array";
_demoValue = "[]";
}
else if (IsObject)
{
_name = "object";
_demoValue = "{}";
if (_schema.Id != null)
_isCustomObject = true;
}
else if (HasFlag(_schema.Type, JsonSchemaType.String))
{
_name = "string";
_demoValue = "string1";
}
else if (HasFlag(_schema.Type, JsonSchemaType.Boolean))
{
_name = "boolean";
_demoValue = true;
}
else if (HasFlag(_schema.Type, JsonSchemaType.Float))
{
_name = "float";
_demoValue = 1.1f;
}
else if (HasFlag(_schema.Type, JsonSchemaType.Integer))
{
_name = "integer";
_demoValue = 1;
}
else if (_schema.Type == JsonSchemaType.Any) _name = "any";
else if (_schema.Type == JsonSchemaType.Null) _name = "null";
else _name = "unknown";
}
}
示例11: Main
static void Main(string[] args)
{
#region ensure latest schema is in program directory
var jsonSchemaGenerator = new JsonSchemaGenerator();
var myType = typeof(Config);
var schema = jsonSchemaGenerator.Generate(myType);
schema.Title = "Bit Rot Watcher Configuration Schema";
using (var writer = new StringWriter())
using (var jsonTextWriter = new JsonTextWriter(writer))
{
schema.WriteTo(jsonTextWriter);
dynamic parsedJson = JsonConvert.DeserializeObject(writer.ToString());
var prettyString = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
using (var fileWriter = new StreamWriter("config.schema.json"))
fileWriter.WriteLine(prettyString);
}
#endregion
#region ensure we have a config file specified
ConfigFilePath = args[0];//Make the naming not suck
if (args.Length == 0 || string.IsNullOrEmpty(ConfigFilePath))
{
WriteOutput("No config file specified.");
return;
}
#endregion
#region load config
try
{
var ConfigFile = new FileInfo(ConfigFilePath);
if (!ConfigFile.Exists)
{
WriteOutput("Configuration file does not exist.");
return;
}
Configuration = JsonConvert.DeserializeObject<Config>(File.ReadAllText(ConfigFile.FullName));
}
catch (Exception ex)
{
WriteOutput($"Error loading specified configuration file. Message: \"{ex.Message}\" Stack: \"{ex.StackTrace}\"");
return;
}
#endregion
#region prep log file stream
FileInfo logFile = LogFile;
if (Configuration.ClearOutputFile && logFile.Exists)
logFile.Delete();
LogStream = File.AppendText(logFile.FullName);
#endregion
#region load database
var dbf = DatabaseFile;
if (!dbf.Exists)
{
WriteOutput("Database file not found, creating new one.");
HashDatabase = new Dictionary<string, WatchedFile>();
}
else
{
HashDatabase = JsonConvert.DeserializeObject<Dictionary<string, WatchedFile>>(File.ReadAllText(dbf.FullName));
}
#endregion
#region process database
foreach (var directory in Configuration.DirectoriesToMonitor.Select(x => new DirectoryInfo(x)))
{
WriteOutput($"Checking root folder \"{directory.FullName}\".");
byte[] currentFileHash;
WatchedFile databaseRecord;
foreach (var file in directory.GetFilesRecurse())
{
currentFileHash = GetFileHash(file);
if (HashDatabase.ContainsKey(file.FullName))
{
databaseRecord = HashDatabase[file.FullName];
if (file.LastWriteTime != databaseRecord.LastWritetime)//File was modified, hash invalid.
{
ModifiedFiles++;
databaseRecord.Hash = currentFileHash;//Update the database's copy so next time we can verify the file.
WriteOutput($"File \"{file.FullName}\" was modified.");
}
else if (StructuralComparisons.StructuralEqualityComparer.Equals(databaseRecord.Hash, currentFileHash))
{
HealthyFiles++;
WriteOutput($"File \"{file.FullName}\" verified succesfully.");
}
else
{
CorruptFiles++;
WriteOutput($"File \"{file.FullName}\" corrupt!!");
}
}
else
{
//.........这里部分代码省略.........
示例12: CreateIfNotExists
public bool CreateIfNotExists()
{
var path = DbSchemaPath;
if (!System.IO.File.Exists(path))
{
var jsonSchemaGenerator = new JsonSchemaGenerator();
var dispanser = typeof(Dispanser);
var schema = jsonSchemaGenerator.Generate(dispanser);
schema.Title = dispanser.Name;
System.IO.File.WriteAllText(path, schema.ToString(), TextEncoding);
return true;
}
return false;
}
示例13: GenerateSchema
public void GenerateSchema()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Session));
// {
// "type": "object",
// "properties": {
// "Name": {
// "required": true,
// "type": [
// "string",
// "null"
// ]
// },
// "Date": {
// "required": true,
// "type": "string"
// }
// }
// }
}
示例14: ReadAsDecimal
public void ReadAsDecimal()
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof (decimal));
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"1.5")))
{
Schema = s
};
decimal? d = reader.ReadAsDecimal();
Assert.AreEqual(1.5m, d);
}
示例15: HandleContractMetadataAsync
public virtual async Task<bool> HandleContractMetadataAsync(ServerActionContext context)
{
try
{
string result = string.Empty;
string actionName = context.HttpContext.Request.Query["action"]?.Trim();
MethodInfo action = null;
if (!string.IsNullOrEmpty(actionName))
{
action = _actionResolver.Resolve(context.Contract, actionName);
}
if (action == null)
{
var contractMetadata = CrateContractMetadata(context);
result = JsonConvert.SerializeObject(
contractMetadata,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
else
{
context.Action = action;
JsonSchema actionSchema = new JsonSchema
{
Properties = new Dictionary<string, JsonSchema>(),
Description = $"Request and response parameters for action '{actionName}'."
};
List<ParameterInfo> actionParameters = BoltFramework.GetSerializableParameters(action).ToList();
if (actionParameters.Any())
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema arguments = new JsonSchema
{
Properties =
actionParameters.ToDictionary(
p => p.Name,
p => generator.Generate(p.ParameterType)),
Required = true,
Type = JsonSchemaType.Object,
};
actionSchema.Properties.Add("request", arguments);
}
if (context.ResponseType != typeof(void))
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
actionSchema.Properties.Add("response", generator.Generate(context.ResponseType));
}
using (var sw = new StringWriter())
{
using (JsonTextWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
actionSchema.WriteTo(jw);
}
result = sw.GetStringBuilder().ToString();
}
}
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = 200;
await context.HttpContext.Response.WriteAsync(result);
return true;
}
catch (Exception e)
{
Logger.LogWarning(
BoltLogId.HandleContractMetadataError,
"Failed to generate Bolt metadata for contract '{0}'. Error: {1}",
context.Contract.Name,
e);
return false;
}
}