JavaRush /בלוג Java /Random-HE /סכימת Json: למה ומי צריך את זה

סכימת Json: למה ומי צריך את זה

פורסם בקבוצה
שלום, נודד. היום אני רוצה לספר לכם על קסם קטן. בטח כבר שמעתם על json. זוהי שפה אוניברסלית כל כך: היא מובנת על ידי מכונות וקריאה בקלות על ידי בני אדם. הנה דוגמה טיפוסית להודעת json:
{
   "помещение":{
      "название":"избушка",
      "разумна":true
   },
   "основание":{
      "тип":"курьи ноги",
      "количество":2
   },
   "проживающие":[
      {
         "Name":"Баба Яга",
         "профиль":"ведьма"
      }
   ],
   "местоположение":{
      "address":"граница леса"
   }
}
זה נוח לתקשר ככה, לא? אם לא ידעת מה זה json לפני כן, עכשיו אתה יודע. איך משתמשים בזה בקוד ג'אווה? Json הפך לפורמט אוניברסלי. זה ראשי תיבות של JavaScript Object Notation, אבל כבר מזמן עבר מעבר ל-Javascript ונמצא בשימוש כמעט בכל מקום. ל- Java יש מספר ספריות המקלות על העבודה עם json. הנה המפורסמים ביותר: אני אשתמש בשני. ישנן 2 גרסאות שלהן : codehaus ו- fasterxml , לא שמתי לב להבדלים, אז אתה יכול להשתמש בכל אחת מהן כאן. הנה קטע קוד:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("сюда json", "сюда класс");
יעזור לתרגם את json לאובייקט. ואנחנו מתקרבים לדבר הכי חשוב. כתיבת מחלקה עבור json זה. אתה יכול לעשות זאת באופן ידני, ליצור מבנה משהו כזה:
-----------------------------------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;

}
השמטתי במיוחד גטרים, סטרים, קונסטרוקטורים ושאר תכונות פוג'ו, אחרת הייתם מתעייפים מבזבוז =) עכשיו תראו כאן:
{
  "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
}
זהו דיאגרמת json של המבנה למעלה. עכשיו הגיע הזמן להסביר למה אתה צריך את זה. זה יבטל את הצורך לכתוב שיעורים ולתחזק אותם. יש פרויקט כל כך טוב jsonschema2pojo . הוא מציע תוספים לבוני פרויקטים (Maven, Gradle) שיכתבו עבורכם את השיעורים הללו בזמן הבנייה. הנה דוגמה מהפרויקט שלי:
<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>
זו התפאורה שלו. הדבר המעניין ביותר נמצא כאן:
<useCommonsLang3>true</useCommonsLang3>
<includeConstructors>true</includeConstructors>
<generateBuilders>true</generateBuilders>
<includeToString>true</includeToString>
<usePrimitives>true</usePrimitives>
זוהי הוראה כיצד לכתוב מחלקה: useCommonsLang3 - השתמש בספריית CommonsLang3 includeConstructors - יכתוב קונסטרוקטור createBuilders - יבנה בונה תבניות includeToString - הוסף לString usePrimitives - הוראה לשימוש בפרימיטיבים איך זה עדיף על קוד שנכתב בבית ?
  1. אתה יכול להתאים אישית שיעורים בשורה אחת. לדוגמה, אתה צריך להוסיף את סיומת Pojo לכל מחלקה. פשוט הוסף את <classNameSuffix>Pojo</classNameSuffix> כדי להרכיב את הפרויקט - וסיימת. אחרת, נצטרך לשנות את השמות של כל מחלקה באופן ידני.

    יש הרבה מהפרמטרים האלה, כדאי לקרוא על כולם במסמכים

  2. אם לפרויקט שלך יש צרכן, יהיה הרבה יותר קל לתת לו סכימות json ולא שיעורי java. כפי שכבר אמרתי, התוכניות הן אוניברסליות והצרכן פשוט ייצור פוג'ו בשפה שלו.

  3. הם הרבה יותר קטנים. הדוגמה למעלה מכילה מידע רב שלא תמיד נחוץ, למשל, דפוסים ודוגמאות. אבל אם תחזיר אותם לקוד ג'אווה, הוא גם יגדל מאוד. ואל תשכח את קוד התבנית, שמצוין בתרשימים על ידי כמה הגדרות בתוסף, אבל אתה צריך לכתוב אותו בקוד בעצמך. וכן, אני יודע לגבי לומבוק, יש אלטרנטיבה.

  4. אין היגיון בפוג'ו. כאשר השיעורים שלך נכתבים בעצמם, מישהו עלול להתפתות להוסיף שיטה שנוחה לו. לא ניתן להוסיף את השיטה לסכימת json, כמו גם למחלקה שנוצרה.

זה כנראה הכל.

סיכום:

ניסיתי להעביר שתוכניות json הן פורמט טוב מאוד לאינטראקציה בין פרויקטים. יום אחד פגשתי אותו בפרויקט, והוא נפל ללב שלי. אני משתמש בהם כמעט בכל מקום. כן, זה לא תמיד נוח, כי כדי לראות את המקורות, אתה צריך להרכיב את הפרויקט. אבל זה פוג'ו, מה שאומר שלא יכול להיות היגיון שם, ולא יהיה כזה עם מעגלים. נ.ב.. לפעמים אני מסביר גרוע, אז הנה סרטון עם דיווח טוב: Kirill Merkushev - יצירת קוד כדרך לפתור בעיות אוטומציה.
הערות
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION