JavaRush /Blog Java /Random-VI /Sơ đồ Json: tại sao và ai cần nó

Sơ đồ Json: tại sao và ai cần nó

Xuất bản trong nhóm
Xin chào, kẻ lang thang. Hôm nay tôi muốn kể cho bạn nghe về một phép thuật nhỏ. Có lẽ bạn đã nghe nói về json. Đây là một ngôn ngữ phổ quát: máy móc có thể hiểu được và con người dễ dàng đọc được. Đây là một ví dụ điển hình về tin nhắn json:
{
   "помещение":{
      "название":"избушка",
      "разумна":true
   },
   "основание":{
      "тип":"курьи ноги",
      "количество":2
   },
   "проживающие":[
      {
         "Name":"Баба Яга",
         "профиль":"ведьма"
      }
   ],
   "местоположение":{
      "address":"граница леса"
   }
}
Thật tiện lợi khi giao tiếp như vậy phải không? Nếu trước đây bạn không biết json là gì thì bây giờ bạn đã biết. Làm thế nào để sử dụng điều này trong mã java? Json đã trở thành một định dạng phổ quát. Nó là viết tắt của Ký hiệu đối tượng JavaScript, nhưng từ lâu đã vượt xa javascript và được sử dụng ở hầu hết mọi nơi. Java có một số thư viện giúp làm việc với json dễ dàng hơn. Dưới đây là những nổi tiếng nhất: Tôi sẽ sử dụng cái thứ hai. Có 2 phiên bản : codehausquickxml , tôi không nhận thấy bất kỳ sự khác biệt nào trong chúng, vì vậy bạn có thể sử dụng bất kỳ phiên bản nào ở đây. Đây là một đoạn mã:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("сюда json", "сюда класс");
sẽ giúp dịch json thành một đối tượng. Và chúng ta đang tiếp cận điều quan trọng nhất. Viết một lớp cho json này. Bạn có thể thực hiện việc này một cách thủ công, tạo một cấu trúc giống như thế này:
-----------------------------------com.fairytale.Base.java-----------------------------------

package com.fairytale;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"type",
"quantity"
})
public class Base {

@JsonProperty("type")
public String type = "";
@JsonProperty("quantity")
public int quantity = 0;

}
-----------------------------------com.fairytale.Hut.java-----------------------------------

package com.fairytale;

import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"room",
"base",
"residents",
"location"
})
public class Hut {

@JsonProperty("room")
public Room room;
@JsonProperty("base")
public Base base;
@JsonProperty("residents")
public List<Resident> residents = new ArrayList<Resident>();
@JsonProperty("location")
public Location location;

}
-----------------------------------com.fairytale.Location.java-----------------------------------

package com.fairytale;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"address"
})
public class Location {

@JsonProperty("address")
public String address = "";

}
-----------------------------------com.fairytale.Resident.java-----------------------------------

package com.fairytale;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"profile"
})
public class Resident {

@JsonProperty("name")
public String name = "";
@JsonProperty("profile")
public String profile = "";

}
-----------------------------------com.fairytale.Room.java-----------------------------------

package com.fairytale;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"reasonable"
})
public class Room {

@JsonProperty("name")
public String name = "";
@JsonProperty("reasonable")
public boolean reasonable = false;

}
Tôi đặc biệt bỏ qua getters, setters, constructor và các thuộc tính pojo khác, nếu không bạn sẽ cảm thấy mệt mỏi vì lãng phí =) Bây giờ hãy xem tại đây:
{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/root.json",
  "type": "object",
  "title": "The Root Schema",
  "required": [
    "room",
    "base",
    "residents",
    "location"
  ],
  "properties": {
    "room": {
      "$id": "#/properties/room",
      "type": "object",
      "title": "The Room Schema",
      "required": [
        "name",
        "reasonable"
      ],
      "properties": {
        "name": {
          "$id": "#/properties/room/properties/name",
          "type": "string",
          "title": "The Name Schema",
          "default": "",
          "examples": [
            "избушка"
          ],
          "pattern": "^(.*)$"
        },
        "reasonable": {
          "$id": "#/properties/room/properties/reasonable",
          "type": "boolean",
          "title": "The Reasonable Schema",
          "default": false,
          "examples": [
            true
          ]
        }
      },
	"additionalProperties": false
    },
    "base": {
      "$id": "#/properties/base",
      "type": "object",
      "title": "The Base Schema",
      "required": [
        "type",
        "quantity"
      ],
      "properties": {
        "type": {
          "$id": "#/properties/base/properties/type",
          "type": "string",
          "title": "The Type Schema",
          "default": "",
          "examples": [
            "курьи ноги"
          ],
          "pattern": "^(.*)$"
        },
        "quantity": {
          "$id": "#/properties/base/properties/quantity",
          "type": "integer",
          "title": "The Quantity Schema",
          "default": 0,
          "examples": [
            2
          ]
        }
      },
	"additionalProperties": false
    },
    "residents": {
      "$id": "#/properties/residents",
      "type": "array",
      "title": "The Residents Schema",
      "items": {
        "$id": "#/properties/residents/items",
        "type": "object",
        "title": "The Items Schema",
        "required": [
          "name",
          "profile"
        ],
        "properties": {
          "name": {
            "$id": "#/properties/residents/items/properties/name",
            "type": "string",
            "title": "The Name Schema",
            "default": "",
            "examples": [
              "Баба Яга"
            ],
            "pattern": "^(.*)$"
          },
          "profile": {
            "$id": "#/properties/residents/items/properties/profile",
            "type": "string",
            "title": "The Profile Schema",
            "default": "",
            "examples": [
              "ведьма"
            ],
            "pattern": "^(.*)$"
          }
        },
	    "additionalProperties": false
      }
    },
    "location": {
      "$id": "#/properties/location",
      "type": "object",
      "title": "The Location Schema",
      "required": [
        "address"
      ],
      "properties": {
        "address": {
          "$id": "#/properties/location/properties/address",
          "type": "string",
          "title": "The Address Schema",
          "default": "",
          "examples": [
            "граница леса"
          ],
          "pattern": "^(.*)$",
		  "additionalProperties": false
        }
      },
	"additionalProperties": false
    }
  },
	"additionalProperties": false
}
Đây là sơ đồ json của cấu trúc trên. Bây giờ là lúc giải thích tại sao bạn cần nó. Nó sẽ loại bỏ sự cần thiết phải viết các lớp và duy trì chúng. Có một dự án hay như vậy jsonschema2pojo . Nó cung cấp các plugin dành cho người xây dựng dự án (Maven, Gradle) sẽ viết các lớp này cho bạn tại thời điểm xây dựng. Đây là một ví dụ từ dự án của tôi:
<plugin>
    <groupId>org.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>0.4.37</version>

    <executions>
        <execution>
            <id>jsonschema2opjo</id>
            <configuration>
                <sourceDirectory>${project.basedir}/src/main/resources/json-schema/</sourceDirectory>
                <targetPackage>tester.model</targetPackage>
                <outputDirectory>${project.basedir}/target/generated-sources/jsonschema/</outputDirectory>
                <useCommonsLang3>true</useCommonsLang3>
                <includeConstructors>true</includeConstructors>
                <generateBuilders>true</generateBuilders>
                <includeToString>true</includeToString>
                <usePrimitives>true</usePrimitives>
            </configuration>
            <goals>
                <goal>generate</goal>
            </goals>
            <phase>generate-sources</phase>
        </execution>
    </executions>
</plugin>
Đây là bối cảnh của anh ấy. Điều thú vị nhất là ở đây:
<useCommonsLang3>true</useCommonsLang3>
<includeConstructors>true</includeConstructors>
<generateBuilders>true</generateBuilders>
<includeToString>true</includeToString>
<usePrimitives>true</usePrimitives>
Đây là hướng dẫn về cách viết một lớp: useCommonsLang3 - sử dụng thư viện CommonsLang3 includeConstructors - sẽ viết một hàm tạo generateBuilders - sẽ xây dựng một trình tạo mẫu includeToString - thêm toString usePrimitive - một hướng dẫn sử dụng các kiểu nguyên thủy. Điều này tốt hơn mã viết ở nhà như thế nào ?
  1. Bạn có thể tùy chỉnh các lớp bằng một dòng. Ví dụ: bạn cần thêm hậu tố Pojo vào mỗi lớp. Chỉ cần thêm <classNameSuffix>Pojo</classNameSuffix> để tập hợp dự án - thế là xong. Nếu không, chúng ta sẽ phải thay đổi tên của từng lớp một cách thủ công.

    Có rất nhiều thông số như vậy, bạn nên đọc về chúng trong tài liệu

  2. Nếu dự án của bạn có người tiêu dùng, việc cung cấp cho nó các lược đồ json thay vì các lớp java sẽ dễ dàng hơn nhiều. Như tôi đã nói, các kế hoạch này có tính phổ biến và người tiêu dùng sẽ chỉ cần tạo ra pojo bằng ngôn ngữ của mình.

  3. Chúng nhỏ hơn nhiều. Ví dụ trên chứa rất nhiều thông tin không phải lúc nào cũng cần thiết, chẳng hạn như mẫu và ví dụ. Nhưng nếu bạn trả chúng về mã java thì nó cũng sẽ phát triển rất nhiều. Và đừng quên mã mẫu, được biểu thị trong sơ đồ bằng một số cài đặt trong plugin, nhưng bạn phải tự viết mã đó vào mã. Và vâng, tôi biết về Lombok, có một giải pháp thay thế.

  4. Không có logic trong pojo. Khi các lớp của bạn được tự viết, ai đó có thể muốn thêm một phương thức thuận tiện cho họ. Không thể thêm phương thức này vào lược đồ json cũng như vào lớp được tạo.

Đó có lẽ là tất cả.

Phần kết luận:

Tôi đã cố gắng truyền đạt rằng sơ đồ json là một định dạng rất tốt để tương tác giữa các dự án. Một ngày nọ, tôi gặp anh ấy trong một dự án và anh ấy đã rơi vào trái tim tôi. Tôi sử dụng chúng hầu như ở khắp mọi nơi. Có, điều này không phải lúc nào cũng thuận tiện, vì để xem các nguồn, bạn cần phải tập hợp dự án. Nhưng đây là pojo, có nghĩa là không thể có logic ở đó và sẽ không có mạch điện nào cả. Tái bút.. đôi khi tôi giải thích không tốt, vì vậy đây là một video có báo cáo hay: Kirill Merkushev - Tạo mã như một cách để giải quyết các vấn đề tự động hóa.
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION