Hi, I’m not fish skin.

Luckily and unluckily, I was a programmer and he was a programmer.

Weekend, I was in the development of the website, he was in the development of games, two people write code together, write bugs together bald, but also have a trace of a different romantic, uncomfortable!

Today, he encountered a Bug in the background, the game can not be started, I come to help troubleshoot, by the way to share some programming knowledge ~

Bug cause

At the start of the game, some configuration is loaded, such as the user name of the player, the difficulty of the level, the initial items of the player, etc.

Since the game was developed in the Java language, he encapsulated these configurations as an object, with the following code:

// Game configuration
class GameConfig {
  / / player name
  String name;
  // Game difficulty
  int difficulty;
  // Player items
  String[] items;
}
Copy the code

For ease of development and debugging, he wrote a default configuration; And to make it easier to manage the default configuration, put it in a separate JSON-formatted file instead of writing it in code.

The default JSON configuration file is as follows:

{
  "name": "yupi"."difficulty": 5."items": ["First-class head"."Class A"]}Copy the code

Then, in the program, read the JSON string in the configuration file, and then convert the JSON string into A Java object through the Gson parsing library. Then, the game configuration information can be obtained, so as to proceed with the next step.

The logical code is as follows:

// Load the game configuration
void loadConfig(a) {
  String jsonStr = loadFile('config.json');
  GameConfig config = new Gson()
    .fromJson(jsonStr, GameConfig.class);
  // Get the player name
  String name = config.getName();
	// More processing. }Copy the code

The whole process looks very simple. Why is an error reported?

Error: JSON parsing error: error: JSON parsing error: error: JSON parsing error: error: JSON parsing error

On closer inspection, alas, this small confused, configuration file unexpectedly entered the wrong, the end of the line missing a necessary quotation mark, of course, will parse failed!

{
  // All lines are missing quotes
  "items": ["First-class head"."Class A]}Copy the code

He said very helpless, no way, the development of the configuration pile more and more, to change to change, do not pay attention to the less a character.

I laughed: THE JSON format is really flexible and powerful, and we often write complex nested JSON in our work. I do know a solution that will help reduce the chances of writing JSON files incorrectly.

He was not impressed. Oh, what? Check with the editor or check site?

I: that can only check the basic syntax, come to come, give you a better kang artifact – JSON Schema!

JSON Schema

One of the advantages of the JSON format is that it is lightweight and does not support writing comments, so you cannot describe fields directly in the file itself.

Therefore, if we use JSON as a configuration file, most of the time we need to look at the document to see the type and scope of each field to write the correct configuration. Not only is this inefficient, but you have to verify that the configuration you’ve written is correct, and you can accidentally write it wrong.

JSON Schema is designed to solve this problem. It is a JSON file and is used to annotate and verify JSON files.

For example, in the game configuration above, the program bugged because it accidentally entered the wrong string array. You can write a JSON Schema to verify that the items field is a valid array 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"}}}Copy the code

In this file, it is specified that the GameConfig type must be Object and the Items property type must be Array.

Next, specify the “$schema” field as the address of the validation file in the data to be verified. For example, in the following JSON configuration, the items field is deliberately set to string instead of array:

{
  "$schema": "https://www.code-nav.cn/latest.json",
  {
  	"name": "yupi"."difficulty": 5."items": "haha"}}Copy the code

So you can check whether the data is valid or not! Many major editors (such as JetBrains Family buckets) can automatically recognize validation files and verify that your JSON input is valid. You can also use JSON Schema Validation Online to validate JSON Schema:

JSON Schema is very powerful. In addition to verifying field types, it can also determine whether a field is required, whether it is a value (regular expression is supported), maximum or minimum value, number of fields, enumeration, and even combination of multiple criteria.

For example, we can also add a check to the difficulty field of our game configuration, which must be a number between 1 and 5. The syntax is as follows:

"difficulty": {
  "type": "number"."minimum": 1."maximum": 5
}
Copy the code

advantages

Now that you know what JSON Schema is, let’s summarize its advantages:

  1. Data formats are described to improve readability and human understanding
  2. Make the machine better understand the data, so as to provide data verification and prompt input functions
  3. Provides a unified data specification syntax for interface formatting validation, automated testing, and even automatic code generation! The JsonSchema2POJO tool, for example, generates Java classes from JSON.

In short, JSON Schema can greatly reduce the cost of communication for developers and ensure the quality of the code. After all, JSON is the most popular data interchange format in front-end development today.


Looking at him a face meng force of appearance, I can not help laughing to: this fish skin is son!

Please give so poor fish skin point support ❤️

Finally, I will give you some programming learning materials:

Directions: t. 1 yb. Co/qOJG

Welcome to read my programming learning and dACHang job hunting experience, no longer confused!

Directions: t. 1 yb. Co/w66s