{
"помещение":{
"название":"избушка",
"разумна":true
},
"основание":{
"тип":"курьи ноги",
"количество":2
},
"проживающие":[
{
"Name":"Баба Яга",
"профиль":"ведьма"
}
],
"местоположение":{
"address":"граница леса"
}
}
Maginhawang makipag-usap nang ganoon, hindi ba? Kung hindi mo alam kung ano ang json noon, alam mo na ngayon. Paano ito gamitin sa java code? Ang Json ay naging isang unibersal na format. Ito ay kumakatawan sa JavaScript Object Notation, ngunit matagal nang lumampas sa javascript at ginagamit halos lahat ng dako. Ang Java ay may ilang mga aklatan na nagpapadali sa pagtatrabaho sa json. Narito ang pinakasikat:
Gagamitin ko ang pangalawa. Mayroong 2 bersyon ng mga ito : codehaus at fasterxml , wala akong napansin na anumang pagkakaiba sa kanila, kaya maaari mong gamitin ang alinman dito. Narito ang isang piraso ng code:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue("сюда json", "сюда класс");
ay makakatulong sa pagsasalin ng json sa isang bagay. At lumalapit kami sa pinakamahalagang bagay. Pagsusulat ng klase para sa json na ito. Maaari mong gawin ito nang manu-mano, lumikha ng isang istraktura na tulad nito:
-----------------------------------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;
}
Partikular kong tinanggal ang mga getter, setter, constructor at iba pang mga katangian ng pojo, kung hindi ay mapapagod ka sa pag-aaksaya =) Ngayon tingnan mo dito:
{
"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
}
Ito ang json diagram ng istraktura sa itaas. Ngayon ay oras na para ipaliwanag kung bakit mo ito kailangan. Aalisin nito ang pangangailangang magsulat ng mga klase at mapanatili ang mga ito. Mayroong isang magandang proyekto jsonschema2pojo . Nag-aalok ito ng mga plugin para sa mga tagabuo ng proyekto (Maven, Gradle) na magsusulat ng mga klase para sa iyo sa oras ng pagbuo. Narito ang isang halimbawa mula sa aking proyekto:
<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>
Ito ang kanyang setting. Ang pinaka-kagiliw-giliw na bagay ay narito:
<useCommonsLang3>true</useCommonsLang3>
<includeConstructors>true</includeConstructors>
<generateBuilders>true</generateBuilders>
<includeToString>true</includeToString>
<usePrimitives>true</usePrimitives>
Ito ay isang pagtuturo kung paano magsulat ng isang klase: useCommonsLang3 - gamitin ang CommonsLang3 library includeConstructors - susulat ng constructor generateBuilders - bubuo ng pattern builder kasamaToString - magdagdag saString usePrimitives - isang pagtuturo na gumamit ng primitives Paano ito mas mahusay kaysa sa home-written code ?
-
Maaari mong i-customize ang mga klase sa isang linya. Halimbawa, kailangan mong idagdag ang Pojo suffix sa bawat klase. Idagdag lang ang <classNameSuffix>Pojo</classNameSuffix> para i-assemble ang proyekto - at tapos ka na. Kung hindi, kailangan nating baguhin nang manu-mano ang mga pangalan ng bawat klase.
Mayroong maraming mga parameter na ito, sulit na basahin ang tungkol sa lahat sa mga doc
-
Kung may consumer ang iyong proyekto, mas madaling bigyan ito ng mga json schemas kaysa sa mga java class. Tulad ng nasabi ko na, ang mga scheme ay unibersal at ang mamimili ay bubuo lamang ng pojo sa kanyang sariling wika.
-
Sila ay mas maliit. Ang halimbawa sa itaas ay naglalaman ng maraming impormasyon na hindi palaging kinakailangan, halimbawa, mga pattern at mga halimbawa. Ngunit kung ibabalik mo ang mga ito sa java code, lalago din ito nang husto. At huwag kalimutan ang tungkol sa code ng template, na ipinahiwatig sa mga diagram ng ilang mga setting sa plugin, ngunit kailangan mong isulat ito sa code mismo. At oo, alam ko ang tungkol sa Lombok, mayroong isang alternatibo.
-
Walang logic sa pojo. Kapag self-written ang iyong mga klase, maaaring matukso ang isang tao na magdagdag ng paraan na maginhawa para sa kanila. Ang pamamaraan ay hindi maaaring idagdag sa json schema, gayundin sa nabuong klase.
GO TO FULL VERSION