在Java中将JSON转换为XLS / CSV

是否有人有任何示例Java代码将JSON文档转换为XLS / CSV文件?我试图在Google上进行搜索,但无济于事。



慕田峪9158850
浏览 868回答 3
3回答

米琪卡哇伊

您只能将JSON数组转换为CSV文件。可以说,您有一个类似于以下内容的JSON:{"infile": [{"field1": 11,"field2": 12,"field3": 13},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"field1": 21,"field2": 22,"field3": 23},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"field1": 31,"field2": 32,"field3": 33}]}让我们看一下将其转换为csv的代码:import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.json.CDL;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;public class JSON2CSV {&nbsp; &nbsp; public static void main(String myHelpers[]){&nbsp; &nbsp; &nbsp; &nbsp; String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";&nbsp; &nbsp; &nbsp; &nbsp; JSONObject output;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output = new JSONObject(jsonString);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONArray docs = output.getJSONArray("infile");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File file=new File("/tmp2/fromJSON.csv");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String csv = CDL.toString(docs);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FileUtils.writeStringToFile(file, csv);&nbsp; &nbsp; &nbsp; &nbsp; } catch (JSONException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}现在,您已经从JSON生成了CSV。它看起来应该像这样:field1,field2,field311,22,3321,22,2331,32,33Maven的依赖就像<dependency>&nbsp; &nbsp; <groupId>org.json</groupId>&nbsp; &nbsp; <artifactId>json</artifactId>&nbsp; &nbsp; <version>20090211</version></dependency>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java