12.4.3 XML→JSON変換
JSON-XML変換APIを使用して,XML形式のデータをJSON形式のデータに変換する場合の実装例を次に示します。
package jp.co.Hitachi.soft.csc.common.converter.jsonxml.sample;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.ws.commons.schema.XmlSchema;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.ConversionErrorInfo;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.XMLtoJSONConverter;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.XMLtoJSONConverterFactory;
import jp.co.Hitachi.soft.csc.common.converter.jsonxml.XSDLoader;
public class ConvJSON {
/**
* XMLファイルの内容をJSONに変換しファイルに書き出す。
*
* @param jsonPath 出力JSONファイルパス
* @param xmlPath 変換対象XMLファイルのパス
* @param xsdPath 変換対象XMLに合致したXSDファイルのパス
*/
void xml2json(String jsonPath, String xmlPath, String xsdPath) {
try {
// XMLファイルからJsonNodeに変換する
JsonNode json = xml2json(xmlPath,xsdPath);
if(json == null) {
// 変換結果が空(XMLとXSDが合致しないなど)
// エラー内容は既にエラー出力に書込まれている。
} else {
// 書き出し用 ObjectMapperを取得
ObjectMapper mapper = new ObjectMapper();
// JsonNodeをファイルに書き出す
mapper.writerWithDefaultPrettyPrinter().writeValue(new File(jsonPath), json);
}
} catch (ParserConfigurationException |
SAXException |
IOException e) {
// 変換失敗
e.printStackTrace();
}
}
/**
* XMLファイルの内容をJSONに変換する。
* @param xmlPath 変換対象XMLファイルのパス
* @param xsdPath 変換対象XMLに合致したXSDファイルのパス
* @return JSONノード
* @throws ParserConfigurationException DocumentBuilderが生成できない
* @throws IOException XMLファイルまたはXSDファイルの読込み時にIO例外が発生した
* @throws SAXException XMLファイルの解析中に例外が発生した。
*/
JsonNode xml2json(String xmlPath, String xsdPath)
throws ParserConfigurationException, SAXException, IOException {
// XMLの読込み
DocumentBuilderFactory builderfactory =
DocumentBuilderFactory.newDefaultInstance();
DocumentBuilder builder = builderfactory.newDocumentBuilder();
Document doc = builder.parse(xmlPath);
// XSDの読込み
XmlSchema schema = XSDLoader.getXmlSchemaLoader()
.load(Path.of(xsdPath));
// 変換実行
return xml2json(doc,schema);
}
/**
* XML DOMをXML Schemaを利用してJsonNodeに変換する
* @param doc 変換対象XML DOMインスタンス
* @param schema 変換対象に合致したXML Schemaインスタンス
* @return 変換結果
*/
JsonNode xml2json(Document doc, XmlSchema schema) {
// XML->JSON変換コンテキストのファクトリの取得
XMLtoJSONConverterFactory factory =
XMLtoJSONConverterFactory.getConverterFactory();
// 変換コンテキストの取得
// オプションを指定する場合は第2引数に指定する。
XMLtoJSONConverter converter = factory.getConverter(schema, null);
// 変換実行
JsonNode node = converter.toJSON(doc);
if(converter.getLastErrors() == null || converter.getLastErrors().size() == 0) {
// エラーは無い
} else {
// 何らかのエラーがあるのでエラー出力に書き出す。
for(ConversionErrorInfo err : converter.getLastErrors()) {
System.err.println(err.toString());
}
}
return node;
}
}