本文整理汇总了C#中Newtonsoft.Json.Schema.JsonSchemaGenerator.Generate方法的典型用法代码示例。如果您正苦于以下问题:C# JsonSchemaGenerator.Generate方法的具体用法?C# JsonSchemaGenerator.Generate怎么用?C# JsonSchemaGenerator.Generate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Newtonsoft.Json.Schema.JsonSchemaGenerator
的用法示例。
在下文中一共展示了JsonSchemaGenerator.Generate方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: 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;
}
}
示例5: 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
{
//.........这里部分代码省略.........
示例6: 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;
}
示例7: 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"
// }
// }
// }
}
示例8: 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";
}
}