12.4.2 JSON→XML変換
JSON-XML変換APIを使用して,JSON形式のデータをXML形式のデータに変換する場合の実装例を次に示します。
package jp.co.Hitachi.soft.csc.common.converter.jsonxml.sample;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.ws.commons.schema.XmlSchema;
import org.w3c.dom.Document;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.ConversionErrorInfo;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.JSONtoXMLConverter;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.JSONtoXMLConverterFactory;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.XSDLoader;
public class CnvXML {
/**
* JSONファイルをXML Schemaを使用してXMLに変換する。
* @param jsonPath JSONファイルのパス
* @param xsdPath XML Schemaファイルのパス
* @return XML Document
*/
Document toXML(String jsonPath, String xsdPath) {
try {
// XML Schemaを読込む
XmlSchema schema = XSDLoader.getXmlSchemaLoader()
.load(Path.of(xsdPath));
// JSON->XML変換コンテキストのファクトリクラスの取得
JSONtoXMLConverterFactory factory =
JSONtoXMLConverterFactory.getConverterFactory();
// JSON->XML変換コンテキストの取得
JSONtoXMLConverter converter = factory.getConverter(schema,null);
// JSON->XML変換の実行
Document doc = converter.toDocument(Path.of(jsonPath));
// 変換エラーリストを取得
List<ConversionErrorInfo> errors = converter.getLastErrors();
if(errors == null || errors.size() == 0) {
// 変換エラーはない
} else {
// 各々の変換エラーを出力
// ConversionErrorInfo.toString()は以下の文字列
// エラーメッセージ (field=フィールド名, value=値)
// ConversionErrorInfoのgetterを利用して、
// カスタムメッセージを出力する事も可能
for(ConversionErrorInfo error : errors) {
System.err.println(error);
}
}
return doc;
} catch(IOException e) {
// XML Schema, JSONの読込み失敗
} catch (ParserConfigurationException e) {
// XML Documentが生成できない。
// DocumentBuilderFactory#newDocumentBuilderがスローした
}
return null;
}
}