JavaでJacksonを使用したJSONスキーマのサポート?
JSONスキーマは、JSONデータの構造を定義するためのJSONベースの形式の仕様です。 JsonSchema クラスは、特定のアプリケーションに必要なJSONデータとその操作方法に関するコントラクトを提供できます。 JsonSchema 検証、ドキュメント、ハイパーリンクナビゲーションを定義できます 、および相互作用制御 JSONデータの。 generateSchema()を使用してJSONスキーマを生成できます JsonSchemaGeneratorのメソッド 、このクラスはJSONスキーマ生成機能をラップします。
public JsonSchema generateSchema(Class<T> type) throws com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import java.util.List;
public class JSONSchemaTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper jacksonObjectMapper = new ObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(jacksonObjectMapper);
JsonSchema schema = schemaGen.generateSchema(Person.class);
String schemaString = jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
System.out.println(schemaString);
}
}
// Person class
class Person {
private String name;
private int age;
private List<String> courses;
private Address address;
public String getName() {
return name;
}
public int getAge(){
return age;
}
public List<String> getCourse() {
return courses;
}
public Address getAddress() {
return address;
}
}
// Address class
class Address {
private String firstLine;
private String secondLine;
private String thirdLine;
public String getFirstLine() {
return firstLine;
}
public String getSecondLine() {
return secondLine;
}
public String getThirdLine() {
return thirdLine;
}
} 出力
{
"type" : "object",
"id" : "urn:jsonschema:Person",
"properties" : {
"name" : {
"type" : "string"
},
"age" : {
"type" : "integer"
},
"address" : {
"type" : "object",
"id" : "urn:jsonschema:Address",
"properties" : {
"firstLine" : {
"type" : "string"
},
"secondLine" : {
"type" : "string"
},
"thirdLine" : {
"type" : "string"
}
}
},
"course" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
} -
JavaでJacksonライブラリを使用してJSONをきれいに印刷しますか?
ジャクソンAPI はJavaベースのライブラリであり、JavaオブジェクトをJSONに、JSONをJavaオブジェクトに変換すると便利です。 Jackson APIは、他のAPIよりも高速で、必要なメモリ領域が少なく、大きなオブジェクトに適しています。 ストリーミングAPI、ツリーモデルを使用して、3つの異なる方法でJSONを処理できます。 およびデータバインディング。 writerWithDefaultPrettyPrinter()を使用してJSONをきれいに印刷できます ObjectMapper クラス、これは ObjectWriterを構築するためのファクトリメソッドです。 デ
-
JavaのJacksonライブラリを使用してJSONをマップとの間で変換しますか?
JSON JacksonはJava用のライブラリであり、非常に強力なデータバインディング機能を備えており、カスタムJavaオブジェクトをJSONにシリアル化し、JSONをJavaオブジェクトに逆シリアル化するフレームワークを提供します。 変換できます JSON から/へ 地図 readValue()を使用する およびwriteValueAsString() com.fasterxml.jackson.databind.ObjectMapperのメソッド クラス。 JSONからマップへ 構文 public <T> T readValue(String content, Typ