问题
I am new to spring batch and there is a requirement for me to read the data from DB and write in to JSON format. whats the best way to do this ? Any api's are there? or we need to write custom writer ? or i need to user JSON libraries such as GSON or JACKSON ? Please guide me...
回答1:
To read data from a relational database, you can use one of the database readers. You can find an example in the spring-batch-samples
repository.
To write JSON data, Spring Batch 4.1.0.RC1
provides the JsonFileItemWriter
that allows you to write JSON data to a file. It collaborates with a JsonObjectMarshaller
to marshal an object to JSON format. Spring Batch provides support for both Gson and Jackson libraries (you need to have the one you want to use in the classpath). You can find more details here.
Hope this helps.
回答2:
You do not need GSON or Jackson Libraries if you DB support JSON.
Example : In SQL Server there is an option to get data out of DB as JSON String instead of resultset.
Reference - https://docs.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-2017
https://docs.microsoft.com/en-us/sql/relational-databases/json/format-nested-json-output-with-path-mode-sql-server?view=sql-server-2017
Example - select (select * from tableName for json path) as jsonString;
This will already give you output in JsonString which you can write to a file.
来源:https://stackoverflow.com/questions/52860863/how-to-write-the-output-from-db-to-a-json-file-using-spring-batch