JavaRush /จาวาบล็อก /Random-TH /โครงการ Json: ทำไมและใครต้องการมัน

โครงการ Json: ทำไมและใครต้องการมัน

เผยแพร่ในกลุ่ม
สวัสดีคุณคนจรจัด วันนี้ฉันอยากจะบอกคุณเกี่ยวกับเวทย์มนตร์เล็กน้อย คุณคงเคยได้ยินเกี่ยวกับ json แล้ว นี่เป็นภาษาสากล: เครื่องจักรเข้าใจได้และมนุษย์อ่านง่าย นี่คือตัวอย่างทั่วไปของข้อความ json:
{
   "помещение":{
      "название":"избушка",
      "разумна":true
   },
   "основание":{
      "тип":"курьи ноги",
      "количество":2
   },
   "проживающие":[
      {
         "Name":"Баба Яга",
         "профиль":"ведьма"
      }
   ],
   "местоположение":{
      "address":"граница леса"
   }
}
สื่อสารแบบนั้นก็สะดวกไม่ใช่เหรอ? หากคุณไม่รู้ว่าก่อนหน้านี้ json คืออะไร ตอนนี้คุณก็รู้แล้ว วิธีการใช้งานสิ่งนี้ในโค้ด Java? Json ได้กลายเป็นรูปแบบสากล ย่อมาจาก JavaScript Object Notation แต่มีการใช้งานมากกว่าจาวาสคริปต์มานานแล้วและมีการใช้กันเกือบทุกที่ Java มีไลบรารี่มากมายที่ทำให้การทำงานกับ json ง่ายขึ้น นี่คือสิ่งที่มีชื่อเสียงที่สุด: ฉันจะใช้อันที่สอง มี 2 ​​เวอร์ชัน: codehausและfastxmlฉันไม่สังเกตเห็นความแตกต่างใด ๆ ดังนั้นคุณสามารถใช้เวอร์ชันใดก็ได้ที่นี่ นี่คือโค้ดบางส่วน:
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;

}
ฉันละเว้น getters, setters, Constructors และคุณลักษณะ pojo อื่น ๆ โดยเฉพาะ ไม่เช่นนั้นคุณจะเบื่อกับการสิ้นเปลือง =) ตอนนี้ดูที่นี่:
{
  "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 - จะเขียน Constructor createBuilders - จะสร้างตัวสร้างรูปแบบ includeToString - เพิ่ม toString usePrimitives - คำแนะนำในการใช้ primitives สิ่งนี้ดีกว่าโค้ดที่เขียนเองที่บ้านอย่างไร ?
  1. คุณสามารถปรับแต่งคลาสได้ด้วยบรรทัดเดียว ตัวอย่างเช่น คุณต้องเพิ่มส่วนต่อท้าย Pojo ให้กับแต่ละคลาส เพียงเพิ่ม <classNameSuffix>Pojo</classNameSuffix> เพื่อประกอบโปรเจ็กต์ - เท่านี้ก็เสร็จเรียบร้อย มิฉะนั้นเราจะต้องเปลี่ยนชื่อของแต่ละคลาสด้วยตนเอง

    มีพารามิเตอร์เหล่านี้มากมาย คุณควรอ่านเกี่ยวกับพารามิเตอร์เหล่านี้ทั้งหมดในเอกสาร

  2. หากโปรเจ็กต์ของคุณมีคอนซูเมอร์ มันจะง่ายกว่ามากที่จะมอบสคีมา json แทนที่จะเป็นคลาส java ดังที่ฉันได้กล่าวไปแล้ว แผนการนี้เป็นสากล และผู้บริโภคก็จะสร้าง pojo ในภาษาของเขาเอง

  3. พวกมันเล็กกว่ามาก ตัวอย่างข้างต้นประกอบด้วยข้อมูลจำนวนมากที่ไม่จำเป็นเสมอไป เช่น รูปแบบและตัวอย่าง แต่ถ้าคุณส่งคืนเป็นโค้ด java มันก็จะเติบโตขึ้นมากเช่นกัน และอย่าลืมเกี่ยวกับโค้ดเทมเพลตซึ่งระบุไว้ในไดอะแกรมด้วยการตั้งค่าสองสามอย่างในปลั๊กอิน แต่คุณต้องเขียนลงในโค้ดด้วยตัวเอง ใช่ ฉันรู้เกี่ยวกับลอมบอก ก็มีทางเลือกอื่น

  4. ไม่มีตรรกะใน pojo เมื่อชั้นเรียนของคุณเขียนเอง อาจมีคนอยากเพิ่มวิธีการที่สะดวกสำหรับพวกเขา ไม่สามารถเพิ่มวิธีการนี้ให้กับสคีมา json รวมถึงคลาสที่สร้างขึ้นได้

นั่นอาจเป็นทั้งหมด

บทสรุป:

ฉันพยายามถ่ายทอดว่าแผนงาน json เป็นรูปแบบที่ดีมากสำหรับการโต้ตอบระหว่างโครงการ วันหนึ่งฉันพบเขาในโครงการหนึ่ง และเขาก็ตกหลุมรักฉัน ฉันใช้มันเกือบทุกที่ ใช่ ไม่สะดวกเสมอไป เพราะในการดูแหล่งที่มา คุณต้องประกอบโปรเจ็กต์ก่อน แต่นี่คือ pojo ซึ่งหมายความว่าไม่มีตรรกะอยู่ที่นั่น และจะไม่มีวงจรด้วย ป.ล.. บางครั้งฉันอธิบายได้ไม่ดี ดังนั้นนี่คือวิดีโอที่มีรายงานที่ดี: Kirill Merkushev - การสร้างโค้ดเป็นวิธีหนึ่งในการแก้ปัญหาระบบอัตโนมัติ
ความคิดเห็น
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION