当前位置:网站首页>3 minutes to understand JSON schema
3 minutes to understand JSON schema
2022-06-24 05:06:00 【Programmer fish skin】
Hello everyone , I'm not fish skin .
Lucky and unfortunate , I am a programmer , He's also a programmer .
Over the weekend , I'm developing a website , He's developing games , Two people write code together , Write together Bug bald , There was a different kind of romance , Not at ease !
today , He met a backstage Bug, The game won't start , Let me help you check , By the way, let's share some programming knowledge ~
Bug cause
At the beginning of the game , First, load some configurations , For example, the user name of the player 、 The difficulty of the level 、 Player's initial props, etc .
Because the game is using Java Language development , He encapsulates these configurations into an object , The code is as follows :
// Game configuration
class GameConfig {
// Player name
String name;
// The difficulty of the game
int difficulty;
// Player items
String[] items;
}For the convenience of development and debugging , He wrote a default configuration ; And for the convenience of managing the default configuration , Put it in a separate JSON Format file , Not in code .
Default JSON The configuration file is as follows :
{
"name": "yupi",
"difficulty": 5,
"items": [" Primary head ", " Secondary a "]
} And then in the program , Read the... In the configuration file JSON character string , Re pass Gson The parsing library will JSON String conversion to Java object , You can get the game configuration information , So as to proceed to the next step .
The logic code is as follows :
// Load game configuration
void loadConfig() {
String jsonStr = loadFile('config.json');
GameConfig config = new Gson()
.fromJson(jsonStr, GameConfig.class);
// Get player name
String name = config.getName();
// More processing
...
}The whole process looks very simple , Why do you report mistakes ?
Print out the abnormal information , Obviously , yes JSON Parsing error :
Take a closer look. , Ah , This little fool , The configuration file was entered incorrectly , A necessary quote is missing at the end of the line , Of course, the parsing failed !
{
// A quote is missing at the end of the line
"items": [" Primary head ", " Secondary a ]
}He said he was helpless , Can't , During development, the configuration heap is more and more 、 Change from one place to another , If you don't pay attention, you'll type less characters .
I laugh so much :JSON The format is really flexible and powerful , We are at work , Also often write some complex nested JSON. I know a way , It can help reduce JSON The probability that the file is written incorrectly .
He didn't think so : Oh , What's the solution ? Check with the editor or check the website ?
I : Then you can only check the basic grammar , Come on, come on , Give you a better artifact —— JSON Schema!
JSON Schema
JSON One of the advantages of the format is its lightweight , It itself does not support writing comments , Therefore, there is no way to describe the fields directly in the file itself .
therefore , If we use JSON To make the configuration file , In most cases, you have to look at the document to see the type of each field 、 Limits , To write the correct configuration . This is not only inefficient , And you must verify whether the configuration written is correct , I accidentally made a mistake .
and JSON Schema Is born to solve this problem , He himself is JSON file , Used to annotate and verify JSON file .
for instance , In the game configuration above , Because you accidentally input the wrong string array, the program went wrong Bug. Then you can write a JSON Schema To verify items Whether the field is a legal array , The code is as follows :
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://www.code-nav.cn/latest.json",
"title": "GameConfig",
"description": " Game configuration ",
"type": "object",
"properties": {
"items": {
"type": "array"
}
}
}In this file , It specifies GameConfig The type of must be object( object ), And items Property type must be array( Array ).
Next, specify... In the data to be verified "$schema" The field is the address of the verification file , Like the following JSON To configure , Deliberately put items The value of the field is set to string( character string ) Not an array :
{
"$schema": "https://www.code-nav.cn/latest.json",
{
"name": "yupi",
"difficulty": 5,
"items": "haha"
}
} In this way, we can check whether the data is legal ! Many mainstream editors ( such as JetBrains Family bucket ) It can automatically identify the verification file , And check your JSON Whether the input is legal . You can also use JSON Schema validation online Wait for online verification JSON Schema To see the effect :
JSON Schema Very powerful , In addition to the verification of field types , It also supports judging whether fields are required 、 Whether it is a value ( regular expression )、 Max min 、 Number of fields 、 Enumeration, etc , It even supports the combination of multiple judgment conditions !
For example, you can also add verification to the difficulty field of our game configuration , Must be 1 To 5 Number between , The grammar is as follows :
"difficulty": {
"type": "number",
"minimum": 1,
"maximum": 5
}advantage
Understand what is JSON Schema after , Summarize its advantages :
- Describe the data format , Improve readability , Help humans understand
- Let the machine understand the data better , So as to provide functions such as data verification and prompt input
- Provides a unified data specification Syntax , It is convenient to realize interface format verification 、 automated testing , You can even use it to automatically generate code ! such as jsonschema2pojo Tools , according to JSON Generate Java class .
All in all , Make good use of JSON Schema, It can greatly reduce the communication cost of developers 、 Just ensure the quality of the code . After all JSON But the most popular data exchange format in front and back-end development today !
Looking at his face , I couldn't help laughing : This fish skin is bad !
Please give such a bad fish skin give the thumbs-up Give me a hand ️
Finally, I'll send you some more Programming learning materials :
The way :https://t.1yb.co/qOJG
Welcome to My programming study and job hunting experience in large factories , No more confusion !
The way :https://t.1yb.co/w66s
边栏推荐
- 『渗透基础』Cobalt Strike基础使用入门_Cobalt Strike联动msfconsole
- Where to buy domain name space? Can the domain name be repeated?
- 梯度下降法介紹-黑馬程序員機器學習講義
- What is the difference between a traditional data center and a cloud computing data center?
- Where is the cheaper domain name? What should I pay attention to when buying a domain name?
- Medical industry EDI overview
- Powerbi - for you who are learning
- What are the advantages of ECS? Is ECS better than VM?
- How to enlarge the ECS page? How to select ECS instance specifications?
- Oracle database prompts no operation permission
猜你喜欢

Hard core observation 553 AI needs to identify almost everyone in the world with hundreds of billions of photos

线性回归的损失和优化,机器学习预测房价

Training methods after the reform of children's programming course

SAP mts/ato/mto/eto topic 8: ATO mode 2 d+ empty mode strategy 85

解析后人类时代类人机器人的优越性

Introduction to gradient descent method - black horse programmer machine learning handout

Introduction to the "penetration foundation" cobalt strike Foundation_ Cobalt strike linkage msfconsole

CTF learning notes 17:iwesec file upload vulnerability-02 file name filtering bypass

Recognize workplus again, not only im but also enterprise mobile application management expert

What are the disadvantages of the free IP address replacement tool?
随机推荐
How does a R & d make a small demand bigger and bigger step by step
Use of golang testing framework goshub
How to select a suitable optical fiber tester
Bi-sql - Select
Tencent conference rest API x-tc-registered parameter policy update notification
How the query address of cloud native monitoring data exposes the public network
Introduction to gradient descent method - black horse programmer machine learning handout
『渗透基础』Cobalt Strike基础使用入门_Cobalt Strike联动msfconsole
让孩子们学习Steam 教育的应用精髓
cuDNN installation
Idea creates a servlet and accesses the 404 message
How to install software on ECs is it expensive to rent ECS
Problem: SQL create stored procedure
Zhang Xiaodan, chief architect of Alibaba cloud hybrid cloud: evolution and development of government enterprise hybrid cloud technology architecture
Application practice of helium decentralized lorawan network in Tencent cloud IOT development platform
oracle数据库提示无操作权限的问题
What is the domain name of the website? How much is a domain name
Spirit breath development log (12)
mini-Web框架:装饰器方式的添加路由 | 黑马程序员
Share 10 creative projects of Gaoxing!