如果您想了解oneOf对象的JsonSchema示例的相关知识,那么本文是一篇不可错过的文章,我们将对json对象写法进行全面详尽的解释,并且为您提供关于.Net使用Newtonsoft.Json.d
如果您想了解oneOf对象的Json Schema示例的相关知识,那么本文是一篇不可错过的文章,我们将对json对象写法进行全面详尽的解释,并且为您提供关于.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程、2023我还不知道的JSON Schema-基础篇、C#使用Newtonsoft的Json.NET进行对象的序列化与反序列化、com.fasterxml.jackson.databind.jsonschema.JsonSchema的实例源码的有价值的信息。
本文目录一览:- oneOf对象的Json Schema示例(json对象写法)
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
- 2023我还不知道的JSON Schema-基础篇
- C#使用Newtonsoft的Json.NET进行对象的序列化与反序列化
- com.fasterxml.jackson.databind.jsonschema.JsonSchema的实例源码
oneOf对象的Json Schema示例(json对象写法)
我试图通过构建验证两种不同对象类型的架构来弄清oneOf的工作原理。例如,一个人(名字,姓氏,运动)和车辆(类型,费用)。
以下是一些示例对象:
{"firstName":"John", "lastName":"Doe", "sport": "football"}{"vehicle":"car", "price":20000}
问题是我做错了什么以及如何解决。这是模式:
{ "description": "schema validating people and vehicles", "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": [ "oneOf" ], "properties": { "oneOf": [ { "firstName": {"type": "string"}, "lastName": {"type": "string"}, "sport": {"type": "string"} }, { "vehicle": {"type": "string"}, "price":{"type": "integer"} } ] }}
当我尝试在此解析器中验证它时:
https://json-schema-validator.herokuapp.com/
我收到以下错误:
[ { "level" : "fatal", "message" : "invalid JSON Schema, cannot continue\nSyntax errors:\n[ {\n \"level\" : \"error\",\n \"schema\" : {\n \"loadingURI\" : \"#\",\n \"pointer\" : \"/properties/oneOf\"\n },\n \"domain\" : \"syntax\",\n \"message\" : \"JSON value is of type array, not a JSON Schema (expected an object)\",\n \"found\" : \"array\"\n} ]", "info" : "other messages follow (if any)"}, { "level" : "error", "schema" : { "loadingURI" : "#", "pointer" : "/properties/oneOf" }, "domain" : "syntax", "message" : "JSON value is of type array, not a JSON Schema (expected an object)", "found" : "array"} ]
答案1
小编典典试试这个:
{ "description" : "schema validating people and vehicles", "type" : "object", "oneOf" : [{ "properties" : { "firstName" : { "type" : "string" }, "lastName" : { "type" : "string" }, "sport" : { "type" : "string" } }, "required" : ["firstName"] }, { "properties" : { "vehicle" : { "type" : "string" }, "price" : { "type" : "integer" } }, "additionalProperties":false }]}
.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询。目前已被微软集成于webapi框架之中,因此,熟练掌握JSON.NET相当重要,这篇文章是零度参考官网整理的示例,通过这些示例,可以全面了解JSON.NET提供的功能。
Newtonsoft.Json的地址:
官网:http://json.codeplex.com/
源码地址:https://github.com/JamesNK/Newtonsoft.Json
Newtonsoft.Json.dll下载:https://github.com/JamesNK/Newtonsoft.Json/releases
1、使用Newtonsoft.Json(JSON.NET)序列化对象,通过Newtonsoft.Json.Formatting将json格式化输出。
Account account = new Account { Email = "1930906722@qq.com",Active = true,CreatedDate =DateTime.Now,Roles = new List<string> { "User","Admin" } }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
2、使用Newtonsoft.Json(JSON.NET)序列化List集合:
List<string> videogames = new List<string> { "HTML5","JavaScript",".net","c#",".net core" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(videogames); Console.WriteLine(json);
执行结果:
3、使用Newtonsoft.Json(JSON.NET)序列化dictionary字典
System.Collections.Generic.Dictionary<string,string> dic = new System.Collections.Generic.Dictionary<string,string> { { "Name","张三" },{ "Age","20" },{ "Email","193090622@qq.com" } }; string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(dic,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json1); Console.WriteLine(""); Console.WriteLine("未格式化的json:"); string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dic,Newtonsoft.Json.Formatting.None); Console.WriteLine(json2);
执行结果:
4、Newtonsoft.Json(JSON.NET)将序列化结果保存到指定的文件:
User movie = new User { Name = "张三",Age = 1993 }; using (System.IO.StreamWriter file = System.IO.File.CreateText(@"F:\UserInfo.txt")) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(file,movie); }
public class User { public string Name { set; get; } public int Age { set; get; } }
执行后保存到文件的结果:
5、Newtonsoft.Json(JSON.NET)基于枚举类型的JsonConverters转换器
List<JosnEnum> list = new List<JosnEnum> { JosnEnum.NotStartus,JosnEnum.Startus }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(list); Console.WriteLine(json); Console.WriteLine(""); System.Collections.Generic.Dictionary<string,int> dic = new System.Collections.Generic.Dictionary<string,int> { {((JosnEnum)(int)JosnEnum.NotStartus).ToString(),(int)JosnEnum.NotStartus},{((JosnEnum)(int)JosnEnum.Startus).ToString(),(int)JosnEnum.Startus} }; string dicJson = Newtonsoft.Json.JsonConvert.SerializeObject(dic); Console.WriteLine(dicJson); Console.WriteLine(""); List<JosnEnum> list2 = new List<JosnEnum> { JosnEnum.NotStartus,JosnEnum.Startus }; string json3 = Newtonsoft.Json.JsonConvert.SerializeObject(list2,new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(json3); Console.WriteLine(""); List<JosnEnum> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JosnEnum>>(json3,new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(string.Join(",",result.Select(c => c.ToString())));
public enum JosnEnum { NotStartus = 0,Startus = 1 }
执行结果:
6、Newtonsoft.Json(JSON.NET)通过JRaw将JS函数序列化到JSON中
JavaScriptSettings settings = new JavaScriptSettings { OnLoadFunction = new Newtonsoft.Json.Linq.JRaw("OnLoad"),OnSucceedFunction = new Newtonsoft.Json.Linq.JRaw("function(e) { alert(e); }") }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(settings,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class JavaScriptSettings { public Newtonsoft.Json.Linq.JRaw OnLoadFunction { get; set; } public Newtonsoft.Json.Linq.JRaw OnSucceedFunction { get; set; } }
7、使用Newtonsoft.Json(JSON.NET)将json反序列化对象
string json = @"{ 'Email': '1930906722@qq.com','Active': true,'CreatedDate': '2016-11-26 20:39','Roles': [ 'User','Admin' ] }"; Account account = Newtonsoft.Json.JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
8、使用Newtonsoft.Json(JSON.NET)反序列化List集合:
string json = @"['Html5','C#','.Net','.Net Core']"; List<string> videogames = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(json); Console.WriteLine(string.Join(",videogames));
执行结果:
9、使用Newtonsoft.Json(JSON.NET)反序列化dictionary字典
string json = @"{'Name': '张三','Age': '23'}"; var htmlAttributes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(json); Console.WriteLine(htmlAttributes["Name"]); Console.WriteLine(htmlAttributes["Age"]);
执行结果:
10、使用Newtonsoft.Json(JSON.NET)序列化var匿名类型,有时候,我们并不需要先定义一个类,然后new一个对象后再进行序列化,JSON.NET支持匿名类型的序列化和反序列化。
var test1 = new { Name = "李四",Age = 26 }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(test1); Console.WriteLine(json); Console.WriteLine(""); var test2 = new { Name = "",Age = 0 }; string json1 = @"{'Name':'张三','Age':'25'}"; var result = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json1,test2); Console.WriteLine(result.Name);
执行结果:
11、Newtonsoft.Json(JSON.NET)用新JSON字符串填充指定对象的属性值
Account account = new Account { Email = "1930906722@qq.com",CreatedDate = DateTime.Now,"Admin" } }; string json = @"{'Active': false,'Roles': ['Expired']}"; Newtonsoft.Json.JsonConvert.PopulateObject(json,account); Console.WriteLine(account.Active); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
12、使用Newtonsoft.Json(JSON.NET)反序列化时可指定构造函数:
首先我们定义如下的类型,我们希望JSON.NET反序列化对象时使用第2个构造函数,我们将第一个默认构造函数屏蔽,标记为私有private修饰符。第2个构造函数需要指定一个website对象作为参数,如果提供的参数为null则抛出异常:
public class Website { public string Url { get; set; } private Website() { } public Website(Website website) { if (website == null) throw new ArgumentNullException("website"); Url = website.Url; } }
现在使用一般的方式反序列化一个JSON字符串。执行出现的结果:
我们发现该序列化方法抛出了异常,并没有按照我们预想的方式进行反序列化,JSON.NET提供如下的方式指定公有构造函数。
string json = @"{'Url':'http://www.cnblogs.com/linJie1930906722/'}"; Website website = Newtonsoft.Json.JsonConvert.DeserializeObject<Website>(json,new Newtonsoft.Json.JsonSerializerSettings { ConstructorHandling = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor }); Console.WriteLine(website.Url);
执行结果:
另外,JSON.NET提供了指定任何构造函数的JsonConstructorAttribute特性,只需要在构造函数上标记,即可指定构造函数。
public class Users { public string UserName { get; private set; } public bool Enabled { get; private set; } public Users() { } [Newtonsoft.Json.JsonConstructor] public Users(string userName,bool enabled) { UserName = userName; Enabled = enabled; } }
string json = @"{""UserName"": ""希特勒"",""Enabled"": true}"; Users user = Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(json); Console.WriteLine(user.UserName);
执行结果:
13、当对象的属性为默认值(0或null)时不序列化该属性
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person1 = new Person(); string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(person1,Newtonsoft.Json.Formatting.Indented,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json1); Console.WriteLine(""); Person person2 = new Person(){Name = "奥巴马"}; string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(person2,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json2);
执行结果:
14、Newtonsoft.Json(JSON.NET)中忽略null值得处理器
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person = new Person { Name = "张三",Age = 46 }; string jsonIncludeNullValues = Newtonsoft.Json.JsonConvert.SerializeObject(person,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(jsonIncludeNullValues); Console.WriteLine(""); string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); Console.WriteLine(json);
执行结果:
15、JSON.NET中循环引用的处理方法
Employee employee1 = new Employee { Name = "张三" }; Employee employee2 = new Employee { Name = "李四" }; employee1.Manager = employee2; employee2.Manager = employee2; string json = Newtonsoft.Json.JsonConvert.SerializeObject(employee1,new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); Console.WriteLine(json);
public class Employee { public string Name { get; set; } public Employee Manager { get; set; } }
执行结果:
16、通过ContractResolver指定属性名首字母小写,通常,在.NET中属性采用PascalCase规则(首字母大写),在JavaScript中属性名使用CamelCase规则(首字母小写),我们希望序列化后的JSON字符串符合CamelCase规则,JSON.NET提供的ContractResolver可以设置属性名小写序列化
public class User { public string Name { set; get; } public int Age { set; get; } }
User person = new User { Name = "张三",Age =52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); Console.WriteLine(json);
执行结果:
17、JSON.NET中通过特性序列化枚举类型
public enum ProductStatus { NotConfirmed,Active,Deleted } public class Product { public string Name { get; set; } [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public ProductStatus Status { get; set; } }
Product user = new Product { Name = @"羽绒服",Status = ProductStatus.Deleted }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(user,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
18、指定需要序列化的属性
[Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)] public class Categroy { //Id不需要序列化 public Guid Id { get; set; } [Newtonsoft.Json.JsonProperty] public string Name { get; set; } [Newtonsoft.Json.JsonProperty] public int Size { get; set; } }
Categroy categroy = new Categroy { Id = Guid.NewGuid(),Name = "内衣",Size = 52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(categroy,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
19、序列化对象时指定属性名
public class Videogame { [Newtonsoft.Json.JsonProperty("name")] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }
Videogame starcraft = new Videogame { Name = "英雄联盟",ReleaseDate = DateTime.Now }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(starcraft,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
20、序列化时指定属性在JSON中的顺序
public class Personl { [Newtonsoft.Json.JsonProperty(Order = 2)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty(Order = 1)] public string LastName { get; set; } }
Personl person = new Personl { FirstName = "张三",LastName = "李四" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
21、反序列化指定属性是否必须有值必须不为null,在反序列化一个JSON时,可通过JsonProperty特性的required指定反序列化行为,当反序列化行为与指定的行为不匹配时,JSON.NET将抛出异常,required是枚举,required.Always表示属性必须有值切不能为null,required.AllowNull表示属性必须有值,但允许为null值。
public class Order { [Newtonsoft.Json.JsonProperty(required = Newtonsoft.Json.required.Always)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty(required = Newtonsoft.Json.required.AllowNull)] public DateTime? ReleaseDate { get; set; } }
string json = @"{ 'Name': '促销订单','ReleaseDate': null }"; Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(json); Console.WriteLine(order.Name); Console.WriteLine(order.ReleaseDate);
执行结果:
22、通过特性指定null值忽略序列化
public class Vessel { public string Name { get; set; } [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public DateTime? launchdate { get; set; } }
Vessel vessel = new Vessel { Name = "张三" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(vessel,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
23、忽略不需要序列化的属性,并不是对象所有属性都要参与序列化,我们可以使用JsonIgnore特性排除不需要序列化的属性,下面示例中的PasswordHash将被忽略。
public class Accounts { public string FullName { get; set; } public string EmailAddress { get; set; } [Newtonsoft.Json.JsonIgnore] public string PasswordHash { get; set; } }
Accounts account = new Accounts { FullName = "admin",EmailAddress = "1930906722@qq.com",PasswordHash = "dfsfgerhtyhsasdhjyujtgwe454811sfsg8d" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account); Console.WriteLine(json);
执行结果:
24、序列化或反序列化时指定日期时间格式,JSON.NET中提供一个名为JsonSerializerSettings的设置对象,可通过此对象设置很多序列化和反序列化的行为,如果要设置JSON.NET序列化输出的日期时间格式,只需要指定格式化字符串即可。通过JsonSerializerSettings的DateFormatString属性指定日期时间格式:
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime CreateDate { get; set; } }
Customer custom = new Customer { FirstName = "张三",LastName = "李四",CreateDate = DateTime.Now }; Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss",Formatting = Newtonsoft.Json.Formatting.Indented }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(custom,settings); Console.WriteLine(json);
执行结果:
2023我还不知道的JSON Schema-基础篇
什么是 JSON
JSON 在前端日常开发中再熟悉不过,往往我们和后端的数据交互都是通过 JSON 来进行传输的。那么具体什么是 JSON 呢?
JSON(JavaScript Object Notation, JS 对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(European Computer Manufacturers Association, 欧洲计算机协会制定的 js 规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
简单来说就是:
- JSON 指的是 JavaScript 对象标记法(JavaScript Object Notation)
- JSON 是一种轻量级的数据交换格式
- JSON 具有自我描述性且易于理解
- JSON 独立于语言*
什么是 JSON Schema
JSON Schema,从字面我们就可以知道,它和 JSON 有紧密的关系。那么具体是什么呢?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.
JSON Schema 可以称为 JSON 模式,是一个提议的 IETF 标准,它可以用来描述和校验你的 JSON 数据。JSON Schema 定义了一套词汇和规则,这套词汇和规则用来定义 JSON 元数据,且元数据也是通过 JSON 数据形式表达的。JSON 元数据定义了 JSON 数据需要满足的规范,规范包括成员、结构、类型、约束等。我们可以通过它来校验我们的 JSON 数据是否有效,是否满足规范。它的作用有些类似于 TypeScript 之于 JavaScript。
它的主要作用:
- 对 JSON 数据格式进行描述
- 提供清晰的人机可读的文档
校验数据
- 自动测试
- 验证提交数据的质量
JSON Schema 示例
假定我们现在有一个 JSON 数据:
{
"productId": 1,
"productName": "A green door",
"price": 12.50,
"tags": [ "home", "green" ]
}
我们来对应声明一个 JSON Schema 如下:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/product.schema.json",
"title": "Product",
"description": "A product",
"type": "object",
"properties": {
"productId": {
"description": "The unique identifier for a product",
"type": "integer"
},
"productName": {
"description": "Name of the product",
"type": "string"
},
"price": {
"description": "The price of the product",
"type": "number",
"exclusiveMinimum": 0
},
"tags": {
"description": "Tags for the product",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
}
},
"required": [ "productId", "productName", "price" ]
}
JSON Schema 关键字
先让我们来看下开头的几个关键字:
$schema
关键字:用来声明当前 JSON Schema 使用的是哪个版本的 JSON Schema 标准,在声明 JSON Schema 时尽量添加上它,虽然它不是必须的。注:该关键字若使用,其值必须使用官方提供的值,不能自己随便写。$id
关键字:为JSON Schema实例声明了一个唯一标识符,并且可以用来声明一个解析$ref 的 URI 时的基础 URI。最佳实践是,每个顶级 JSON Schema 实例都应该将 $id 设置为一个由你自己控制的域内的绝对 URI。title
和description
关键字:仅用于描述性的作用,可以省略。type
关键字:用于验证 JSON 数据的第一个约束,在上述例子中,JSON 数据必须是一个对象。
上面几个关键字是针对 Schema 的一些设置和注释,针对对应的 JSON 数据中每个字段的描述,都在 properties 中,具体每种格式的字段相关的描述,我们稍后具体说明。让我们先看下最后一个关键字 required,它用来描述 JSON 数据中哪些字段是必须的,对应的值必须是数组格式。比如我们在更新文章时,提交的字段中文章 id 会是必须的;上面 JSON 数据中 productId 是必须的。
下面让我们具体看下 JSON 数据中不同类型的字段对应的描述关键字都有哪些。
JSON 数据中每个字段的描述都对应一个 type,type 对应的基本类型主要包括:
类型 | 描述 |
---|---|
string | 字符串型,双引号包裹的 Unicode 字符和反斜杠转义字符 |
number | 数字型,包括整型(int)和浮点数型(float) |
boolean | 布尔型,true 或 false |
object | 对象型,无序的键:值对集合 |
array | 数组型,有序的值序列 |
null | 空型 |
其中,针对类型 string、number、array 和 object 有一些相关的关键字:
string
关键字 描述 schema 有效值 json 数据验证 maxLength 最大长度 大于等于 0 的整数 字符串的长度必须小于等于该值 minLength 最小长度 大于等于 0 的整数 字符串的长度必须大于等于该值 pattern 模式 字符串,必须是有效的正则表达式 当字符串符合正则表达式时,通过验证 number
关键字 描述 Schema 有效值 json 数据验证 multipleOf 整数倍 大于 0 的 JSON 数 当 JSON 实例的值是其整数倍的时候,通过验证 maximum 最大值 一个 JSON 数 当 JSON 实例的值小于等于 maximum 的时候,通过验证 exclusiveMaximum 包含最大值 布尔值,必须与 maximum 一起使用 当其为 true 的时候,JSON 实例不能等于 maximum 的值 minimum 最小值 一个 JSON 数 当 JSON 实例的值大于等于 minimum 的时候,通过验证 exclusiveMinimum 包含最小值 布尔值,必须与 minimum 一起使用 当其为 true 的时候,JSON 实例不能等于 minimum 的值 array
关键字 描述 Schema 有效值 json 数据验证 items 定义元素 必须是 Schema 实例对象或者 Schema 实例对象的数组 用于定义 array 中的元素类型 additionalItems 额外项校验 布尔值或 Schema 实例对象 当 items 为 Schema 实例的数组,additionalItems 为 false 时,json 数据长度必须小于等于 items 长度,如果 additionalItems 是 Schema 实例,则 items 关键字指定的 Schema 实例数组没有匹配到的其他元素都要符合该实例 maxItems 长度限制 大于等于 0 的整数 array 实例的长度必须小于等于 maxItems 的值 minItems 长度限制 大于等于 0 的整数 array 实例的长度必须大于等于 minItems 的值 uniqueItems 唯一值 布尔值,默认值 false 当 uniqueItems 为 true 的时候,array 实例不能有重复值。 object
关键字 描述 Schema 有效值 json 数据验证 properties 属性 属性的值必须都是有效的 Schema 实例对象 用于定义属性列表 maxProperties 最大属性个数 大于等于 0 的整数 object 实例的属性个数必须小于等于 maxProperties 的值 minProperties 最小属性个数 大于等于 0 的整数 object 实例的属性个数必须大于等于 minProperties 的值 required 必须属性 字符串数组,至少必须有一个元素,数组内不能有重复值 object 实例必须有所有 required 定义的属性 patternProperties 按属性名校验 必须是有效的 Scheme 实例对象 Scheme 实例的每一个属性的键都是一个正则表达式,值都是一个 Schema 实例。 指定符合正则表达式的属性的校验规则。 additionalProperties 额外属性校验 Scheme 实例对象或布尔值 为 false 时不允许拥有除了 properties 和 patternProperties 匹配到的属性外的属性,如果为 Scheme 实例,则没有匹配到的属性要符合该 Scheme 另外,还有一些通用关键字
关键字 描述 Schema 有效值 json 数据验证 enum 数据枚举 必须是数组,而且数组里面的元素至少必须有一个而且不能有重复值。 当 json 实例的值存在于 enum 列表中时,通过验证 type 定义类型 可以是字符串或者字符串数组,取值必须在 JSON 基本类型范围内 校验 JSON 实例的类型是否符合定义 allOf 数据验证 必须是 Schema 实例对象数组,而且数组里面的元素至少必须有一个而且不能有重复 JSON 实例满足其中所有的 Schema 时,通过验证 anyOf 数据验证 同 allOf JSON 实例满足其中某一个 Schema 时,通过验证 oneOf 数据验证 同 allOf JSON 实例刚好只满足其中某一个 Schema 时,通过验证 not 数据验证 必须是个有效的 Schema 实例对象 如果不满足 JSON Schema 的定义,则通过验证 const 数据验证 JSON 基本类型 如果 JSON 实例的值和该关键字指定的值相同,则通过校验。
小结
本次我们主要是初步了解了 JSON Schema 和 JSON 的关系,以及 JSON Schema 的一些基础内容。JSON Schema 的构成主要依托于一些关键字,以此来确定一个 JSON 的数据结构描述。看到这里,可能我们还没有体会到它的作用,我们会在后续具体来看一下它是如何发挥作用,在哪些场景下为我们提供便利的,敬请期待。
参考:
1.JSON Schema 入门
2.JSON Schema Reference
3.在线 JSON 转 JSON Schema
C#使用Newtonsoft的Json.NET进行对象的序列化与反序列化
Json.NET是一种流行的.NET高性能JSON框架,C#中可以使用Newtonsoft的Json.NET进行对象的序列化与反序列化。C#中通过使用json.net可以快速的生成json和解释json,可以在序列化时忽略对象中的某些属性,简化json的大小。同时可以使用LINQ进行json的查询和编辑。
C# json使用之Json.NET(1)
Json.NET是一种流行的.NET高性能JSON框架,C#中使用Newtonsoft的Json.NET进行序列化与反序列化。
C# json使用之Json.NET(2)
介绍C# json.net的各种参数设置以及属性设置,通过官方文档进行详细说明。包含:Serialization Attributes、Serialization Callbacks、Serialization Error Handling、Preserving Object References、…
C# json使用之Json.NET(3)
C#中使用json.net进行json数据的序列化。本文介绍json.net的各种设置属性,包括:JSON 在JSON中序列化日期、减少序列化的JSON大小、反序列化部分JSON片段、条件属性序列化、使用ContractResolver进行序列化、使用序列化跟踪进行调试。
C# json使用之Json.NET(4)——LINQ to JSON
LINQ to JSON是一个用于处理JSON对象的API。 它的设计考虑了LINQ,以便快速查询和创建JSON对象。 LINQ to JSOn位于Newtonsoft.Json.Linq命名空间下。
C# json使用之Json.NET(5)——特别篇
介绍了json.NET的性能优化问题(通过输入流来解释json)、使用JSON模式验证JSON、手动读写JSON,Json.NET提供了JsonReader和JsonWriter类、json和xml之间的转换。
C# json使用之Json.NET(6)——使用示例
json.net使用示例程序代码。
相关文章:
【c#教程】C# 数据类型
通过静态局部变量看C,C++,C#,Java,PHP的特点
com.fasterxml.jackson.databind.jsonschema.JsonSchema的实例源码
public JsonNode getSchema(SerializerProvider paramSerializerProvider,Type paramType) { ObjectNode localObjectNode = createSchemaNode("array",true); if (paramType != null) { JavaType localJavaType = paramSerializerProvider.constructType(paramType); if (localJavaType.isArrayType()) { Class localClass = ((ArrayType)localJavaType).getContentType().getRawClass(); if (localClass == Object.class) { localObjectNode.put("items",JsonSchema.getDefaultSchemaNode()); return localObjectNode; } JsonSerializer localJsonSerializer = paramSerializerProvider.findValueSerializer(localClass,this._property); JsonNode localJsonNode; if ((localJsonSerializer instanceof SchemaAware)) localJsonNode = ((SchemaAware)localJsonSerializer).getSchema(paramSerializerProvider,null); else localJsonNode = JsonSchema.getDefaultSchemaNode(); localObjectNode.put("items",localJsonNode); } } return localObjectNode; }
public JsonNode getSchema(SerializerProvider paramSerializerProvider,Type paramType) { ObjectNode localObjectNode1 = createSchemaNode("object",true); if ((paramType instanceof ParameterizedType)) { Type[] arrayOfType = ((ParameterizedType)paramType).getActualTypeArguments(); if (arrayOfType.length == 2) { JavaType localJavaType1 = paramSerializerProvider.constructType(arrayOfType[0]); JavaType localJavaType2 = paramSerializerProvider.constructType(arrayOfType[1]); ObjectNode localObjectNode2 = JsonNodeFactory.instance.objectNode(); for (Enum localEnum : (Enum[])localJavaType1.getRawClass().getEnumConstants()) { JsonSerializer localJsonSerializer = paramSerializerProvider.findValueSerializer(localJavaType2.getRawClass(),this._property); JsonNode localJsonNode; if ((localJsonSerializer instanceof SchemaAware)) localJsonNode = ((SchemaAware)localJsonSerializer).getSchema(paramSerializerProvider,null); else localJsonNode = JsonSchema.getDefaultSchemaNode(); localObjectNode2.put(paramSerializerProvider.getConfig().getAnnotationIntrospector().findEnumValue(localEnum),localJsonNode); } localObjectNode1.put("properties",localObjectNode2); } } return localObjectNode1; }
/** * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} * to generate <a href="http://json-schema.org/">JSON schema</a> for * given type. * * @param type The type for which to generate schema */ public JsonSchema generateJsonSchema(Class<?> type) throws JsonMappingException { if (type == null) { throw new IllegalArgumentException("A class must be provided"); } /* no need for embedded type information for JSON schema generation (all * type information it needs is accessible via "untyped" serializer) */ JsonSerializer<Object> ser = findValueSerializer(type,null); JsonNode schemaNode = (ser instanceof SchemaAware) ? ((SchemaAware) ser).getSchema(this,null) : JsonSchema.getDefaultSchemaNode(); if (!(schemaNode instanceof ObjectNode)) { throw new IllegalArgumentException("Class " + type.getName() + " would not be serialized as a JSON object and therefore has no schema"); } return new JsonSchema((ObjectNode) schemaNode); }
@Override public JsonNode getSchema(SerializerProvider provider,Type typeHint) throws JsonMappingException { ObjectNode o = createSchemaNode("array",true); if (typeHint != null) { JavaType javaType = provider.constructType(typeHint); if (javaType.isArrayType()) { Class<?> componentType = ((ArrayType) javaType).getContentType().getRawClass(); // 15-Oct-2010,tatu: We can't serialize plain Object.class; but what should it produce here? Untyped? if (componentType == Object.class) { o.put("items",JsonSchema.getDefaultSchemaNode()); } else { JsonSerializer<Object> ser = provider.findValueSerializer(componentType,_property); JsonNode schemaNode = (ser instanceof SchemaAware) ? ((SchemaAware) ser).getSchema(provider,null) : JsonSchema.getDefaultSchemaNode(); o.put("items",schemaNode); } } } return o; }
@SuppressWarnings("unchecked") @Override public JsonNode getSchema(SerializerProvider provider,Type typeHint) throws JsonMappingException { ObjectNode o = createSchemaNode("object",true); if (typeHint instanceof ParameterizedType) { Type[] typeArgs = ((ParameterizedType) typeHint).getActualTypeArguments(); if (typeArgs.length == 2) { JavaType enumType = provider.constructType(typeArgs[0]); JavaType valueType = provider.constructType(typeArgs[1]); ObjectNode propsNode = JsonNodeFactory.instance.objectNode(); Class<Enum<?>> enumClass = (Class<Enum<?>>) enumType.getRawClass(); for (Enum<?> enumValue : enumClass.getEnumConstants()) { JsonSerializer<Object> ser = provider.findValueSerializer(valueType.getRawClass(),null) : JsonSchema.getDefaultSchemaNode(); propsNode.put(provider.getConfig().getAnnotationIntrospector().findEnumValue((Enum<?>)enumValue),schemaNode); } o.put("properties",propsNode); } } return o; }
/** * Attempt to add the output of the given {@link BeanPropertyWriter} in the given {@link ObjectNode}. * Otherwise,add the default schema {@link JsonNode} in place of the writer's output * * @param propertiesNode Node which the given property would exist within * @param provider Provider that can be used for accessing dynamic aspects of serialization * processing * * {@link BeanPropertyFilter#depositSchemaProperty(BeanPropertyWriter,ObjectNode,SerializerProvider)} * * @since 2.1 */ public void depositSchemaProperty(ObjectNode propertiesNode,SerializerProvider provider) throws JsonMappingException { JavaType propType = getSerializationType(); // 03-Dec-2010,tatu: SchemaAware REALLY should use JavaType,but alas it doesn't... Type hint = (propType == null) ? getGenericPropertyType() : propType.getRawClass(); JsonNode schemaNode; // Maybe it already has annotated/statically configured serializer? JsonSerializer<Object> ser = getSerializer(); if (ser == null) { // nope Class<?> serType = getRawSerializationType(); if (serType == null) { serType = getPropertyType(); } ser = provider.findValueSerializer(serType,this); } boolean isOptional = !isrequired(provider.getAnnotationIntrospector()); if (ser instanceof SchemaAware) { schemaNode = ((SchemaAware) ser).getSchema(provider,hint,isOptional) ; } else { schemaNode = JsonSchema.getDefaultSchemaNode(); } propertiesNode.put(getName(),schemaNode); }
public JsonSchema generateJsonSchema(Class<?> paramClass) { if (paramClass == null) throw new IllegalArgumentException("A class must be provided"); JsonSerializer localJsonSerializer = findValueSerializer(paramClass,null); JsonNode localJsonNode1; if ((localJsonSerializer instanceof SchemaAware)) localJsonNode1 = ((SchemaAware)localJsonSerializer).getSchema(this,null); else localJsonNode1 = JsonSchema.getDefaultSchemaNode(); JsonNode localJsonNode2 = localJsonNode1; if (!(localJsonNode1 instanceof ObjectNode)) throw new IllegalArgumentException("Class " + paramClass.getName() + " would not be serialized as a JSON object and therefore has no schema"); return new JsonSchema((ObjectNode)localJsonNode2); }
public JsonNode getSchema(SerializerProvider paramSerializerProvider,true); Object localObject = null; if (paramType != null) { JavaType localJavaType = paramSerializerProvider.constructType(paramType).getContentType(); localObject = localJavaType; if ((localJavaType == null) && ((paramType instanceof ParameterizedType))) { Type[] arrayOfType = ((ParameterizedType)paramType).getActualTypeArguments(); if (arrayOfType.length == 1) localObject = paramSerializerProvider.constructType(arrayOfType[0]); } } if ((localObject == null) && (this._elementType != null)) localObject = this._elementType; if (localObject != null) { Class localClass = ((JavaType)localObject).getRawClass(); JsonNode localJsonNode = null; if (localClass != Object.class) { JsonSerializer localJsonSerializer = paramSerializerProvider.findValueSerializer((JavaType)localObject,this._property); boolean bool = localJsonSerializer instanceof SchemaAware; localJsonNode = null; if (bool) localJsonNode = ((SchemaAware)localJsonSerializer).getSchema(paramSerializerProvider,null); } if (localJsonNode == null) localJsonNode = JsonSchema.getDefaultSchemaNode(); localObjectNode.put("items",localJsonNode); } return localObjectNode; }
public void depositSchemaProperty(ObjectNode paramObjectNode,SerializerProvider paramSerializerProvider) { JavaType localJavaType = getSerializationType(); Object localObject; if (localJavaType == null) localObject = getGenericPropertyType(); else localObject = localJavaType.getRawClass(); JsonSerializer localJsonSerializer1 = getSerializer(); JsonSerializer localJsonSerializer2 = localJsonSerializer1; if (localJsonSerializer1 == null) { Class localClass1 = getRawSerializationType(); Class localClass2 = localClass1; if (localClass1 == null) localClass2 = getPropertyType(); localJsonSerializer2 = paramSerializerProvider.findValueSerializer(localClass2,this); } boolean bool; if (!isrequired()) bool = true; else bool = false; JsonNode localJsonNode; if ((localJsonSerializer2 instanceof SchemaAware)) localJsonNode = ((SchemaAware)localJsonSerializer2).getSchema(paramSerializerProvider,(Type)localObject,bool); else localJsonNode = JsonSchema.getDefaultSchemaNode(); paramObjectNode.put(getName(),localJsonNode); }
@Test public void exampleCode() throws Exception { ObjectMapper om = new ObjectMapper(); om.configure(SerializationFeature.INDENT_OUTPUT,true); Geocoder geocoder = new Geocoder(); System.out.println(om.writeValueAsstring(geocoder.resolve("Rancho Cordova,US"))); System.out.println(om.writeValueAsstring(geocoder.resolve("Москва является удивительным"))); JsonSchema schema = om.generateJsonSchema(Location.class); System.out.println(schema.toString()); }
@Override public JsonNode getSchema(SerializerProvider provider,Type typeHint) throws JsonMappingException { return (_valueSerializer instanceof SchemaAware) ? ((SchemaAware) _valueSerializer).getSchema(provider,null) : JsonSchema.getDefaultSchemaNode(); }
@Test public void testWriteSchema() throws Exception { JsonSchema jsonSchema = objectMapper.generateJsonSchema(Page.class); }
public JsonNode getSchema(SerializerProvider paramSerializerProvider,Type paramType) { if ((this._valueSerializer instanceof SchemaAware)) return ((SchemaAware)this._valueSerializer).getSchema(paramSerializerProvider,null); return JsonSchema.getDefaultSchemaNode(); }
@Override public JsonNode getSchema(SerializerProvider provider,Type typeHint) throws JsonMappingException { /* 15-Jan-2010,tatu: This should probably be rewritten,given that * more information about content type is actually being explicitly * passed. So there should be less need to try to re-process that * information. */ ObjectNode o = createSchemaNode("array",true); JavaType contentType = null; if (typeHint != null) { JavaType javaType = provider.constructType(typeHint); contentType = javaType.getContentType(); if (contentType == null) { // Could still be parametrized (Iterators) if (typeHint instanceof ParameterizedType) { Type[] typeArgs = ((ParameterizedType) typeHint).getActualTypeArguments(); if (typeArgs.length == 1) { contentType = provider.constructType(typeArgs[0]); } } } } if (contentType == null && _elementType != null) { contentType = _elementType; } if (contentType != null) { JsonNode schemaNode = null; // 15-Oct-2010,tatu: We can't serialize plain Object.class; but what should it produce here? Untyped? if (contentType.getRawClass() != Object.class) { JsonSerializer<Object> ser = provider.findValueSerializer(contentType,_property); if (ser instanceof SchemaAware) { schemaNode = ((SchemaAware) ser).getSchema(provider,null); } } if (schemaNode == null) { schemaNode = JsonSchema.getDefaultSchemaNode(); } o.put("items",schemaNode); } return o; }
/** * Generate <a href="http://json-schema.org/">Json-schema</a> * instance for specified class. * * @param t The class to generate schema for * @return Constructed JSON schema. */ public JsonSchema generateJsonSchema(Class<?> t) throws JsonMappingException { return _serializerProvider(getSerializationConfig()).generateJsonSchema(t); }
今天关于oneOf对象的Json Schema示例和json对象写法的分享就到这里,希望大家有所收获,若想了解更多关于.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程、2023我还不知道的JSON Schema-基础篇、C#使用Newtonsoft的Json.NET进行对象的序列化与反序列化、com.fasterxml.jackson.databind.jsonschema.JsonSchema的实例源码等相关知识,可以在本站进行查询。
本文标签: