12.4.1 JSON→XSD変換
JSON-XML変換APIを使用して,JSON形式のデータをXSD形式のデータに変換する場合の実装例を次に示します。
package jp.co.Hitachi.soft.csc.common.converter.jsonxml.sample;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import org.apache.ws.commons.schema.XmlSchema;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.JSONtoXSDConverter;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.JSONtoXSDConverterFactory;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.XmlSchemaUtils;
public class GenXSD {
/**
* JSONファイルからXML Schemaファイルを作成する。
* @param jsonPath 入力JSONファイルパス名
* @param xsdPath 出力XSDファイルパス名
*/
public void toXSDFile(String jsonPath, String xsdPath) {
try {
// JSONtoXSDConverterFactoryインスタンスを取得する
JSONtoXSDConverterFactory factory = JSONtoXSDConverterFactory.getConverterFactory();
// JSONtoXSDConverterの実装インスタンスを取得する
JSONtoXSDConverter converter = factory.getConverter(null);
// 入力JSONファイルからXmlSchemaインスタンスを生成する。
XmlSchema schema = converter.toSchema(Path.of(jsonPath));
// OuputStreamを取得し
try(OutputStream os = Files.newOutputStream(Path.of(xsdPath))) {
// XSDファイルを書込む
XmlSchemaUtils.printXmlSchema(schema, os);
}
} catch (IOException e) {
// JSONファイルが読込めない、JSONファイルの形式が不正、
// XSDファイルに書込めない等
e.printStackTrace();
}
}
/**
* JSONファイルからXML Schemaファイルを作成する。
* ルートタグ、無名タグをカスタマイズする
* @param jsonPath 入力JSONファイルパス名
* @param xsdPath 出力XSDファイルパス名
*/
public void toXSDFile(String jsonPath, String xsdPath, String rootTag, String unnamedTag) {
try {
// JSONtoXSDConverterFactoryインスタンスを取得する
JSONtoXSDConverterFactory factory = JSONtoXSDConverterFactory.getConverterFactory();
// オプションデータ格納用mapの宣言
Properties options = null; // <- Map<Object,Object>でもOK
if((rootTag != null && rootTag.length() > 0) ||
(unnamedTag != null && unnamedTag.length() > 0)) {
// rootTag, unnamedTagのいずれかが設定されている。
options = new Properties();
if(rootTag != null && rootTag.length() > 0) {
// rootTagをカスタマイズする場合
options.put(
JSONtoXSDConverterFactory.ROOT_TAG_OPTION_KEY,
rootTag);
}
if(unnamedTag != null && unnamedTag.length() > 0) {
// 無名タグをカスタマイズする場合
options.put(
JSONtoXSDConverterFactory.UNNAMED_TAG_PREFIX_OPTION_KEY,
unnamedTag);
}
}
// JSONtoXSDConverterの実装インスタンスを取得する
JSONtoXSDConverter converter = factory.getConverter(options);
// 入力JSONファイルからXmlSchemaインスタンスを生成する。
XmlSchema schema = converter.toSchema(Path.of(jsonPath));
// OuputStreamを取得し
try(OutputStream os = Files.newOutputStream(Path.of(xsdPath))) {
// XSDファイルを書込む
XmlSchemaUtils.printXmlSchema(schema, os);
}
} catch (ReflectiveOperationException e) {
// JSONtoXSDConverterFactoryが取得できなかった。
// デフォルトの状態では発生しない。
// jsonxml.JSONtoXSDConverterFactoryClass システムプロパティに
// 設定したクラスが存在しない場合に発生する。
e.printStackTrace();
} catch (IOException e) {
// JSONファイルが読込めない、JSONファイルの形式が不正、
// XSDファイルに書込めない等
e.printStackTrace();
}
}
}