你好,流浪者。今天我想跟大家講一個小魔法。您可能已經聽說過 json。這是一種通用語言:機器可以理解,人類也可以輕鬆閱讀。下面是一個 json 訊息的典型範例:
{
"помещение":{
"название":"избушка",
"разумна":true
},
"основание":{
"тип":"курьи ноги",
"количество":2
},
"проживающие":[
{
"Name":"Баба Яга",
"профиль":"ведьма"
}
],
"местоположение":{
"address":"граница леса"
}
}
這樣溝通起來很方便不是嗎?如果您以前不知道 json 是什麼,現在您知道了。如何在java程式碼中使用這個?Json 已成為通用格式。它代表 JavaScript 物件表示法,但早已超出了 javascript 範圍,幾乎無所不在。Java 有幾個函式庫可以讓 json 的使用變得更容易。以下是最著名的:
我將使用第二個。它們有兩個版本: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;
}
我特意省略了 getter、setter、建構子和其他 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 - 將編寫構造函數 generateBuilders - 將構建模式構建器 includeToString - 添加 toString usePrimitives - 使用原語的說明這比家庭編寫的程式碼更好嗎?
-
您可以用一行自訂類別。例如,您需要為每個類別新增Pojo後綴。只需新增 <classNameSuffix>Pojo</classNameSuffix> 來組裝專案 - 就完成了。否則,我們將不得不手動更改每個類別的名稱。
這些參數有很多,值得在文件中閱讀它們
-
如果你的專案有一個消費者,那麼給它 json 模式而不是 java 類別會容易得多。正如我已經說過的,這些方案是通用的,消費者只需用自己的語言產生 pojo 即可。
-
它們要小得多。上面的範例包含許多並不總是必需的信息,例如模式和範例。但如果將它們返回到java程式碼中,它也會成長很多。不要忘記模板程式碼,它在圖表中由插件中的幾個設定指示,但您必須自己在程式碼中編寫它。是的,我知道龍目島,還有另一個選擇。
-
pojo 中沒有邏輯。當您的類別是自己編寫的時,有人可能會想添加對他們來說方便的方法。該方法無法加入 json 架構以及產生的類別。
GO TO FULL VERSION