JavaRush /Java Blog /Random-TK /Json shemasy: näme üçin we kime mätäç

Json shemasy: näme üçin we kime mätäç

Toparda çap edildi
Salam, gezelenç. Bu gün size azajyk jady hakda aýdasym gelýär. Json hakda eýýäm eşiden bolsaňyz gerek. Munuň ýaly ähliumumy dil: maşynlar tarapyndan düşünilýär we adamlar aňsatlyk bilen okaýarlar. Ine, json habarynyň adaty mysaly:
{
   "помещение":{
      "название":"избушка",
      "разумна":true
   },
   "основание":{
      "тип":"курьи ноги",
      "количество":2
   },
   "проживающие":[
      {
         "Name":"Баба Яга",
         "профиль":"ведьма"
      }
   ],
   "местоположение":{
      "address":"граница леса"
   }
}
Munuň ýaly habarlaşmak amatly, şeýlemi? Jsonyň nämedigini bilmeseňiz, indi bilýärsiňiz. Muny java kodunda nädip ulanmaly? Json ähliumumy formata öwrüldi. JavaScript Object Notation diýmekdir, ýöne javascript-den köp geçdi we hemme ýerde diýen ýaly ulanylýar. Java-da json bilen işlemegi aňsatlaşdyrýan birnäçe kitaphanasy bar. Ine iň meşhurlary: Ikinjisini ulanaryn. Olaryň 2 wersiýasy bar : kodhaus we fastxml , men olarda hiç hili tapawudy görmedim, şonuň üçin şu ýerde ulanyp bilersiňiz. Ine bir kod:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("сюда json", "сюда класс");
json-a bir obýekte terjime etmäge kömek eder. Iň möhüm zada ýakynlaşýarys. Bu json üçin synp ýazmak. Muny el bilen edip bilersiňiz, şuňa meňzeş bir gurluş döredip bilersiňiz:
-----------------------------------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;

}
Getterleri, sazlaýjylary, konstruktorlary we beýleki pojo häsiýetlerini aýratyn goýdum, ýogsam isrip etmekden ýadarsyňyz =) Indi şu ýere serediň:
{
  "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
}
Bu ýokardaky gurluşyň json diagrammasy. Indi munuň näme üçin zerurdygyny düşündirmegiň wagty geldi. Sapak ýazmak we olary dowam etdirmek zerurlygyny ýok eder. Şeýle gowy taslama jsonschema2pojo bar . Taslama gurluşykçylary üçin (Maven, Gradle) plaginleri hödürleýär, bu sapaklary wagtynda ýazar. Ine, taslamamdan bir mysal:
<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>
Bu onuň sazlamasy. Iň gyzykly zat şu ýerde:
<useCommonsLang3>true</useCommonsLang3>
<includeConstructors>true</includeConstructors>
<generateBuilders>true</generateBuilders>
<includeToString>true</includeToString>
<usePrimitives>true</usePrimitives>
Bu synpy nädip ýazmalydygy barada görkezme: useCommonsLang3 - CommonsLang3 kitaphanasyny ulanyňConstructors - konstruktor generatorBuilders ýazar - konstruktor dörederToString - toString usePrimitives goşar - primitiwleri ulanmak boýunça görkezme Öýde ýazylan koddan nädip gowy? ?
  1. Sapaklary bir setir bilen düzüp bilersiňiz. Mysal üçin, her klasa Pojo goşulmasyny goşmaly. Taslamany ýygnamak üçin diňe <classNameSuffix> Pojo </classNameSuffix> goşuň - gutardyňyz. Otherwiseogsam, her synpyň atlaryny el bilen üýtgetmeli bolarys.

    Bu parametrleriň köpüsi bar, bularyň hemmesini resminamalarda okamaly

  2. Taslamaňyzda sarp ediji bar bolsa, java sapaklaryna däl-de, oňa json shemalaryny bermek has aňsat bolar. Öň hem aýdyşym ýaly, shemalar ähliumumy we sarp ediji diňe öz dilinde pojo döreder.

  3. Olar has kiçi. Aboveokardaky mysalda hemişe zerur däl köp sanly maglumatlar bar, mysal üçin, nagyşlar we mysallar. Themöne olary java koduna gaýtaryp berseňiz, ol hem köpeler. Plagindäki birnäçe sazlamalar bilen diagrammalarda görkezilen şablon koduny ýatdan çykarmaň, ýöne kodda özüňiz ýazmalysyňyz. Hawa, Lombok hakda bilýärin, başga bir alternatiwa bar.

  4. Pojo-da logika ýok. Sapaklaryňyz özbaşdak ýazylsa, kimdir biri özlerine amatly usul goşup biler. Usuly json shemasyna, döredilen klasa goşup bolmaz.

Bularyň hemmesi ähtimal.

Netije:

Json shemalarynyň taslamalaryň arasynda täsirleşmek üçin gaty gowy formatdygyny görkezmäge synanyşdym. Bir gün men bir taslama bilen tanyşdym, ol meniň ýüregime düşdi. Olary hemme ýerde diýen ýaly ulanýaryn. Hawa, bu elmydama amatly däl, sebäbi çeşmeleri görmek üçin taslamany ýygnamaly. Thisöne bu pojo, bu ýerde logika bolup bilmez we zynjyrlar bilen bolmaz. PS .. käwagt erbet düşündirýärin, şonuň üçin gowy hasabatly wideo: Kirill Merkuşew - Awtomatlaşdyryş meselelerini çözmegiň usuly hökmünde kod döretmek.
Teswirler
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION