mongodb json_在MongoDB和Spring Batch中将XML转换为JSON和原始使用
mongodb json
總覽
為什么將XML轉(zhuǎn)換為JSON以在MongoDB中原始使用?
由于MongoDB使用JSON文檔存儲(chǔ)記錄,就像表和行將記錄存儲(chǔ)在關(guān)系數(shù)據(jù)庫(kù)中一樣,我們自然需要將XML轉(zhuǎn)換為JSON。
某些應(yīng)用程序可能需要存儲(chǔ)原始(未修改的)JSON,因?yàn)樵谌绾螛?gòu)造數(shù)據(jù)方面存在不確定性。
有數(shù)百種基于XML的標(biāo)準(zhǔn) 。 如果應(yīng)用程序要處理不遵循相同標(biāo)準(zhǔn)的XML文件,則數(shù)據(jù)的結(jié)構(gòu)將存在不確定性。
為什么要使用Spring Batch?
Spring Batch提供了可重用的功能,這些功能在處理大量記錄時(shí)是必不可少的,而其他功能則可以實(shí)現(xiàn)高容量和高性能的批處理作業(yè)。 Spring網(wǎng)站已很好地記錄了Spring Batch 。
有關(guān)Spring Batch的其他教程,請(qǐng)參閱我以前的文章“ 使用Spring Batch處理CSV” 。
0 –將XML轉(zhuǎn)換為JSON以在MongoDB中與Spring Batch示例應(yīng)用程序一起使用
該示例應(yīng)用程序轉(zhuǎn)換XML文檔,該XML文檔是用于配置音樂(lè)播放列表的“策略”。 該策略旨在類(lèi)似于真實(shí)的網(wǎng)絡(luò)安全配置文檔。 它是一個(gè)簡(jiǎn)短的文檔,但說(shuō)明了如何搜索復(fù)雜的XML文檔。
我們將采用本教程的方法是處理各種樣式的XML文件。 我們希望能夠處理意外情況。 這就是為什么我們保持?jǐn)?shù)據(jù)“原始”的原因。
1 –項(xiàng)目結(jié)構(gòu)
它是典型的Maven結(jié)構(gòu)。 我們?yōu)榇耸纠龖?yīng)用程序提供了一個(gè)軟件包。 XML文件位于src / main / resources中 。
2 –項(xiàng)目依賴(lài)性
除了典型的Spring Boot依賴(lài)關(guān)系之外,我們還包括嵌入式MongoDB數(shù)據(jù)庫(kù)和JSON處理的依賴(lài)關(guān)系。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.michaelcgood</groupId><artifactId>michaelcgood-spring-batch-mongodb</artifactId><version>0.0.1</version><packaging>jar</packaging><name>michaelcgood-spring-batch-mongodb</name><description>Michael C Good - XML to JSON + MongoDB + Spring Batch Example</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.7.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-batch</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>de.flapdoodle.embed</groupId><artifactId>de.flapdoodle.embed.mongo</artifactId><version>1.50.5</version></dependency><dependency><groupId>cz.jirutka.spring</groupId><artifactId>embedmongo-spring</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20170516</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>3 – XML文檔
這是為本教程創(chuàng)建的示例策略文檔。 它的結(jié)構(gòu)基于真實(shí)的網(wǎng)絡(luò)安全策略文檔。
- 請(qǐng)注意,文檔的父項(xiàng)是Policy標(biāo)記。
- 重要信息位于“組”標(biāo)簽內(nèi)。
- 查看標(biāo)記內(nèi)的值,例如Policy中的ID或status中的日期。
在這個(gè)小文檔中有很多信息需要考慮。 例如,還有XML名稱(chēng)空間(xmlns)。 在本教程的其余部分中,我們不會(huì)涉及到這一點(diǎn),但是根據(jù)您的目標(biāo),可能需要為其添加邏輯。
<?xml version="1.0"?> <Policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" style="STY_1.1" id="NRD-1"><status date="2017-10-18">draft</status><title xmlns:xhtml="http://www.w3.org/1999/xhtml">Guide to the Configuration of Music Playlist</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >This guide presents a catalog of relevantconfiguration settings for a playlist that I listen to while I work on software development.<html:br xmlns:html="http://www.w3.org/1999/xhtml"/><html:br xmlns:html="http://www.w3.org/1999/xhtml"/>Providing myself with such guidance reminds me how to efficientlyconfigure my playlist. Lorem ipsum <html:i xmlns:html="http://www.w3.org/1999/xhtml">Lorem ipsum,</html:i> and Lorem ipsum. Some example<html:i xmlns:html="http://www.w3.org/1999/xhtml">Lorem ipsum</html:i>, which are Lorem ipsum.</description><Group id="remediation_functions"><title xmlns:xhtml="http://www.w3.org/1999/xhtml" >Remediation functions used by the SCAP Security Guide Project</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >XCCDF form of the various remediation functions as used byremediation scripts from the SCAP Security Guide Project</description><Value id="is_the_music_good" prohibitChanges="true" ><title xmlns:xhtml="http://www.w3.org/1999/xhtml" >Remediation function to fix bad playlist</title><description xmlns:xhtml="http://www.w3.org/1999/xhtml" >Function to fix bad playlist.Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsum</description><value>function fix_bad_playlist {# Load function arguments into local variablesLorem ipsumLorem ipsumLorem ipsum# Check sanity of the inputif [ $# Lorem ipsum ]thenecho "Usage: Lorem ipsum"echo "Aborting."exit 1fi}</value></Value></Group></Policy>4 – MongoDB配置
在下面,我們指定我們使用的是嵌入式MongoDB數(shù)據(jù)庫(kù),使它可被捆綁在便利注釋@SpringBootApplication中的組件掃描發(fā)現(xiàn),并指定mongoTemplate將是bean。
package com.michaelcgood;import java.io.IOException; import cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.*; import com.mongodb.MongoClient;@Configuration public class MongoConfig {private static final String MONGO_DB_URL = "localhost";private static final String MONGO_DB_NAME = "embeded_db";@Beanpublic MongoTemplate mongoTemplate() throws IOException {EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();mongo.setBindIp(MONGO_DB_URL);MongoClient mongoClient = mongo.getObject();MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME);return mongoTemplate;} }5 –處理XML到JSON
我們的Spring Batch Job的step1()包含調(diào)用三個(gè)方法,以幫助將XML轉(zhuǎn)換為JSON。 我們將分別進(jìn)行審查。
@Beanpublic Step step1() {return stepBuilderFactory.get("step1").tasklet(new Tasklet() {@Overridepublic RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {// get path of file in src/main/resourcesPath xmlDocPath = Paths.get(getFilePath());// process the file to jsonString json = processXML2JSON(xmlDocPath);// insert json into mongodbinsertToMongo(json);return RepeatStatus.FINISHED;}}).build();}5.1 – getFilePath()
此方法只是獲取作為參數(shù)傳遞給方法processXML2JSON的文件路徑。
注意:
- ClassLoader正在幫助我們?cè)谫Y源文件夾中找到XML文件。
5.2 – processXML2JSON(xmlDocPath)
getFilePath返回的字符串作為參數(shù)傳遞到此方法中。 從XML文件的字符串創(chuàng)建一個(gè)JSONOBject。
// takes a parameter of xml path and returns json as a stringprivate String processXML2JSON(Path xmlDocPath) throws JSONException {String XML_STRING = null;try {XML_STRING = Files.lines(xmlDocPath).collect(Collectors.joining("\n"));} catch (IOException e) {e.printStackTrace();}JSONObject xmlJSONObj = XML.toJSONObject(XML_STRING);String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);System.out.println("PRINTING STRING :::::::::::::::::::::" + jsonPrettyPrintString);return jsonPrettyPrintString;}5.3 – insertToMongo(json)
我們將已解析的JSON插入MongoDB文檔中。 然后,我們?cè)?#64;Autowired mongoTemplate的幫助下將此文檔插入名為“ foo”的集合中。
// inserts to our mongodbprivate void insertToMongo(String jsonString){Document doc = Document.parse(jsonString);mongoTemplate.insert(doc, "foo");}6 –查詢(xún)MongoDB
我們的Spring Batch Job的step2()包含我們的MongoDB查詢(xún)。
- mongoTemplate.collectionExists基于集合的存在返回一個(gè)布爾值。
- mongoTemplate.getCollection(“ foo”)。find()返回集合中的所有文檔。
- alldocs.toArray()返回一個(gè)DBObjects數(shù)組。
- 然后,我們將調(diào)用以下三種方法,我們將在下面分別進(jìn)行回顧。
6.1 –第一個(gè)查詢(xún)
該查詢(xún)的目標(biāo)是找到一個(gè)樣式為“ STY_1.1”的文檔。 為此,我們需要記住樣式在文檔中的位置。 它是政策的產(chǎn)物; 因此,我們將其作為Policy.style來(lái)處理 。
該查詢(xún)的另一個(gè)目標(biāo)是僅返回策略的id字段。 它也是政策的產(chǎn)物。
通過(guò)調(diào)用以下方法返回結(jié)果: mongoTemplate.findOne(query,String.class,“ foo”); 。 輸出為String,因此第二個(gè)參數(shù)為String.class 。 第三個(gè)參數(shù)是我們的集合名稱(chēng)。
public String doCollect(){Query query = new Query();query.addCriteria(Criteria.where("Policy.style").is("STY_1.1")).fields().include("Policy.id");String result = mongoTemplate.findOne(query, String.class, "foo");return result;}6.2 –第二個(gè)查詢(xún)
第二個(gè)查詢(xún)和第一個(gè)查詢(xún)之間的區(qū)別是返回的字段。 在第二個(gè)查詢(xún)中,我們返回Value,它是Policy和Group的子級(jí)。
public String doCollectTwo(){Query query = new Query();query.addCriteria(Criteria.where("Policy.style").is("STY_1.1")).fields().include("Policy.Group.Value");String result = mongoTemplate.findOne(query, String.class, "foo");return result;}6.3 –第三次查詢(xún)
第三個(gè)查詢(xún)的條件不同。 我們只想返回ID為“ NRD-1”且狀態(tài)日期為“ 2017-10-18”的文檔 。 我們只想返回兩個(gè)字段:title和description,它們都是Value的子級(jí)。
請(qǐng)?jiān)谙旅娴难菔局袇⒖糥ML文檔或打印的JSON,以進(jìn)一步澄清查詢(xún)。
public String doCollectThree(){Query query = new Query();query.addCriteria(Criteria.where("Policy.id").is("NRD-1").and("Policy.status.date").is("2017-10-18")).fields().include("Policy.Group.Value.title").include("Policy.Group.Value.description");String result = mongoTemplate.findOne(query, String.class, "foo");return result;}7 –Spring批處理作業(yè)
作業(yè)從步驟1開(kāi)始,然后調(diào)用步驟2。
@Beanpublic Job xmlToJsonToMongo() {return jobBuilderFactory.get("XML_Processor").start(step1()).next(step2()).build();}8 – @SpringBootApplication
這是一個(gè)帶有靜態(tài)void main和@SpringBootApplication的標(biāo)準(zhǔn)類(lèi)。
package com.michaelcgood;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;@SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class SpringBatchMongodb {public static void main(String[] args) {SpringApplication.run(SpringBatchMongodb.class, args);} }9 –演示
9.1 –步驟1
JSON打印為字符串。 由于輸出很長(zhǎng),因此我在下面的描述中省略了輸出。
Executing step: [step1] PRINTING STRING :::::::::::::::::::::{"Policy": {"Group": {"Value": {"prohibitChanges": true,"description": {9.2 –步驟2
我剪切了結(jié)果以格式化博客文章的輸出。
Executing step: [step2]檢查集合是否存在
Status of collection returns :::::::::::::::::::::true顯示所有對(duì)象
list of db objects returns:::::::::::::::::::::[{ "_id" : { "$oid" : "59e7c0324ad9510acf5773c0"} , [..]只需返回Policy的ID
RESULT:::::::::::::::::::::{ "_id" : { "$oid" : "59e7c0324ad9510acf5773c0"} , "Policy" : { "id" : "NRD-1"}}要查看打印到控制臺(tái)的其他結(jié)果,請(qǐng)從Github分叉/下載代碼并運(yùn)行該應(yīng)用程序。
10 –結(jié)論
我們已經(jīng)審查了如何將XML轉(zhuǎn)換為JSON,如何將JSON存儲(chǔ)到MongoDB,以及如何在數(shù)據(jù)庫(kù)中查詢(xún)特定結(jié)果。
進(jìn)一步閱讀:
- MongoTemplate
- JSON.org
源代碼在 Github上
翻譯自: https://www.javacodegeeks.com/2017/10/converting-xml-json-raw-use-mongodb-spring-batch.html
mongodb json
總結(jié)
以上是生活随笔為你收集整理的mongodb json_在MongoDB和Spring Batch中将XML转换为JSON和原始使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 日本合资品牌手提电脑(日本合资品牌手提电
- 下一篇: hp电脑无法识别硬盘(hp看不到硬盘)