JavaRush /Blog Jawa /Random-JV /Skema Json: kenapa lan sapa sing butuh

Skema Json: kenapa lan sapa sing butuh

Diterbitake ing grup
Halo, pengembara. Dina iki aku arep nyritakake babagan sihir cilik. Sampeyan mbokmenawa wis krungu bab json. Iki minangka basa universal: dimangerteni dening mesin lan gampang diwaca dening manungsa. Punika conto khas pesen json:
{
   "помещение":{
      "название":"избушка",
      "разумна":true
   },
   "основание":{
      "тип":"курьи ноги",
      "количество":2
   },
   "проживающие":[
      {
         "Name":"Баба Яга",
         "профиль":"ведьма"
      }
   ],
   "местоположение":{
      "address":"граница леса"
   }
}
Iku trep kanggo komunikasi kaya ngono, ta? Yen sampeyan ora ngerti apa json sadurunge, saiki sampeyan ngerti. Kepiye cara nggunakake iki ing kode java? Json wis dadi format universal. Iku stands for JavaScript Object Notation, nanging wis suwe ngluwihi javascript lan digunakake meh ing endi wae. Jawa duwe sawetara perpustakaan sing nggawe nggarap json luwih gampang. Ing ngisor iki sing paling misuwur: Aku bakal nggunakake sing kapindho. Ana 2 versi : codehaus lan fasterxml , aku ora weruh bedane, mula sampeyan bisa nggunakake salah siji ing kene. Iki minangka potongan kode:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("сюда json", "сюда класс");
bakal mbantu nerjemahake json menyang obyek. Lan kita nyedhaki sing paling penting. Nulis kelas kanggo json iki. Sampeyan bisa nindakake iki kanthi manual, nggawe struktur kaya iki:
-----------------------------------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;

}
Aku khusus ngilangi getter, setter, konstruktor lan atribut pojo liyane, yen ora, sampeyan bakal kesel mbuang =) Saiki deleng ing kene:
{
  "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
}
Iki minangka diagram json saka struktur ing ndhuwur. Saiki wektune kanggo nerangake kenapa sampeyan butuh. Bakal ngilangi kabutuhan nulis kelas lan njaga. Ana proyek apik jsonschema2pojo . Nawakake plugin kanggo tukang proyek (Maven, Gradle) sing bakal nulis kelas kasebut kanggo sampeyan nalika mbangun. Mangkene conto saka proyekku:
<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>
Iki setelane. Sing paling menarik yaiku ing kene:
<useCommonsLang3>true</useCommonsLang3>
<includeConstructors>true</includeConstructors>
<generateBuilders>true</generateBuilders>
<includeToString>true</includeToString>
<usePrimitives>true</usePrimitives>
Iki minangka instruksi babagan carane nulis kelas: useCommonsLang3 - gunakake perpustakaan CommonsLang3 includeConstructors - bakal nulis konstruktor generateBuilders - bakal mbangun pola builder includeToString - nambah menyangString usePrimitives - instruksi kanggo nggunakake primitif Kepiye iki luwih apik tinimbang kode sing ditulis ing omah ?
  1. Sampeyan bisa ngatur kelas kanthi siji baris. Contone, sampeyan kudu nambah seselan Pojo kanggo saben kelas. Cukup tambahake <classNameSuffix>Pojo</classNameSuffix> kanggo ngrakit proyek - lan sampeyan wis rampung. Yen ora, kita kudu ngganti jeneng saben kelas kanthi manual.

    Ana akeh paramèter kasebut, sampeyan kudu maca babagan kabeh ing docs

  2. Yen proyek sampeyan duwe konsumen, bakal luwih gampang menehi skema json tinimbang kelas java. Kaya sing wis dakkandhakake, skema kasebut universal lan konsumen mung bakal ngasilake pojo ing basane dhewe.

  3. Padha luwih cilik. Conto ing ndhuwur ngemot akeh informasi sing ora perlu, contone, pola lan conto. Nanging yen sampeyan bali menyang kode java, uga bakal tuwuh akeh. Lan aja lali babagan kode cithakan, sing dituduhake ing diagram dening sawetara setelan ing plugin, nanging sampeyan kudu nulis dhewe ing kode kasebut. Lan ya, aku ngerti babagan Lombok, ana alternatif.

  4. Ora ana logika ing pojo. Nalika kelas sampeyan ditulis dhewe, ana wong sing bisa digodha kanggo nambah metode sing trep kanggo dheweke. Cara kasebut ora bisa ditambahake menyang skema json, uga ing kelas sing digawe.

Sing mbok menawa kabeh.

Kesimpulan:

Aku nyoba nyatakake yen skema json minangka format sing apik banget kanggo interaksi antarane proyek. Ing sawijining dina aku ketemu karo dheweke ing proyek, lan dheweke tiba ing atiku. Aku digunakake meh nang endi wae. Ya, iki ora mesthi trep, amarga kanggo ndeleng sumber, sampeyan kudu ngumpulake proyek kasebut. Nanging iki pojo, kang tegese ora bisa logika ana, lan ora bakal ana karo sirkuit. PS .. kadhangkala aku nerangake kurang apik, dadi iki video kanthi laporan sing apik: Kirill Merkushev - Generasi kode minangka cara kanggo ngatasi masalah otomatisasi.
Komentar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION