java - 如何使用 json.JSONArray 将多维 Json 数组解析为 CSV

标签 java csv export-to-csv json

这是我的 Json 响应:

{
"value": [
    {
        "type": "school",
        "id": 12,
        "name": "NNPS",
        "city": "CA",
        "geo_position": {
            "latitude": 52.52437,
            "longitude": 13.41053
        }
    },
    {
        "type": "College",
        "id": 44,
        "name": "PEC",
        "city": "PE",
        "geo_position": {
            "latitude": 45.50298,
            "longitude": 10.04366
        }
    }
  ]
}

这是我使用“json.JSONArray”库的java代码:

while ((csvdata= br.readLine()) != null) {
  JSONObject output= new JSONObject(csvdata);
  JSONArray docs = output.getJSONArray("value");
  String csv = CDL.toString(docs);
  FileUtils.writeStringToFile(file, csv);
 }

当我检查 csv 文件时,它显示如下:

enter image description here 但应该是这样的:

enter image description here 我正处于编码阶段的最初阶段,目前正在对其进行改进。请给我一些建议:) 我应该如何更改它?

最佳答案

您应该重新设置纬度和经度的级别。这对我有用

while ((csvdata= br.readLine()) != null) {
   JSONObject output= new JSONObject(csvdata);
   JSONArray docs = output.getJSONArray("value");

   for(int i=0; i<docs.length();i++){
       JSONObject geo_pos =  (JSONObject)(docs.getJSONObject(i).getJSONObject("geo_position"));
       docs.getJSONObject(i).put("latitude", geo_pos.get("latitude"));
       docs.getJSONObject(i).put("longitude", geo_pos.get("longitude"));
       docs.getJSONObject(i).remove("geo_position");
   }       

   String csv = CDL.toString(docs);
   FileUtils.writeStringToFile(file, csv);
 }

关于java - 如何使用 json.JSONArray 将多维 Json 数组解析为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446862/

相关文章:

java - 如何向选项卡添加图标

java - 读取文件时无限循环

java - 不同 Eclipse Java 项目的不同制表符/空格策略

java - 简单字符串拆分

java - 如何将实体对象绑定(bind)到本地 @Transient 属性?

python - 使用 Flask 流式传输生成的 CSV

Python csv 模块拆分字符串,而不仅仅是字段

python - Pandas DataFrame.to_csv() OSError : [Errno 22] Invalid argument and PermissionError: [Errno 13] Permission denied

R:导出和导入列表到 .txt 文件

xml - 用python解析xml(查找带有特定文本的标签)