Java 将 JSON 转换为 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20388119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:35:21  来源:igfitidea点击:

Converting JSON to CSV

javajsonrestcsv

提问by chiru

I have a JSON of the format below and I am trying to write to CSV:

我有以下格式的 JSON,我正在尝试写入 CSV:

{
    "results": [{

            "geo_position": {
                "Field1": 11,
                "Filed2": 12
            },
            "Field3": 13,
            "Filed4": 14,
            "Field5": 15
        },

        {
            "geo_position": {
                "Field1": 21,
                "Filed2": 22
            },
            "Field3": 23,
            "Filed4": 24,
            "Filed5": 25
        }
    ]
}


I am expecting output like:

我期待输出如下:

field1,field2,field3,field4,field5
11,12,13,14,15
21,22,23,24,25


I am getting output CSV as below:

我得到的输出 CSV 如下:

    geo_position,field3,field4,field5
   {Field1:11,Field2:12}, 13,14,15
   {Field2:21,Field2:22},23,24,25


My java code:

我的Java代码:

JSONObject jsonObj = new JSONObject(jsonArray);
System.out.println(jsonObj);
JSONArray docs = jsonObj.getJSONArray("results");
File file=new File("C:/fromJSON2.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);

Can some one help me to figure out why I am getting in different format. What should I do to get in the format I expect?

有人可以帮助我弄清楚为什么我会采用不同的格式。我应该怎么做才能达到我期望的格式?

回答by Jules G.M.

your JSON structure is

你的 JSON 结构是

{
"results":
[
    {
        "geo_position": {"Field1":11,"Filed2":12},
        "Field3":13,
        "Filed4":14,
        "Field5":15
    },

    {
        "geo_position":{"Field1":21,"Filed2":22},
        "Field3":23,
        "Filed4":24,
        "Filed5":25
    }

]
}

For it to work about the way you want it to work, it should be something like:

为了让它按照您希望的方式工作,它应该是这样的:

{
"results":
[
    {
        "Field1":11,
        "Filed2":12,
        "Field3":13,
        "Filed4":14,
        "Field5":15
    },

    {
        "Field1":21,
        "Filed2":22,
        "Field3":23,
        "Filed4":24,
        "Filed5":25
    }

]
}

what you could do something like

你可以做些什么

for(int i = 0; i<resultsJSONArray.length(); ++i){ 
    if(resultsJSONArray.get(i).has("geo_position")) {
          String names[] = JSONObject.getNames(resultsJSONArray.get(i).get("geo_position")));
          for(int i = 0; i<names().length; ++i) {                                       
              resultsJSONArray.get(i).put(names[i],resultsJSONArray.get(i).get("geo_position").get(names[i]));
          }
          JSONObject.getNames(resultsJSONArray.get(i).remove("geo_position"));
    }
}

回答by skap

There are some typos in the data.

数据中有一些错别字。

You can try json2flatfor converting JSON docs to get an equivalent CSV representation.
If you want to try for more JSON doc click here.

您可以尝试使用json2flat转换 JSON 文档以获得等效的 CSV 表示。
如果您想尝试更多 JSON 文档,请单击此处

For the JSON data :

对于 JSON 数据:

{
    "results": [{

            "geo_position": {
                "Field1": 11,
                "Field2": 12
            },
            "Field3": 13,
            "Field4": 14,
            "Field5": 15
        },

        {
            "geo_position": {
                "Field1": 21,
                "Field2": 22
            },
            "Field3": 23,
            "Field4": 24,
            "Field5": 25
        }
    ]
}

Equivalent CSV representation :

等效的 CSV 表示:

results/Field3,results/Field4,results/Field5,results/geo_position/Field1,results/geo_position/Field2
13.0,14.0,15.0,11.0,12.0
23.0,24.0,25.0,21.0,22.0

The code is also preety simple.

代码也很简单。

JFlat flatMe = new JFlat(jsonString);
flatMe
    .json2Sheet()
    .headerSeparator("/")
    .write2csv("test.csv");

This will write the result to test.csv file.

这会将结果写入 test.csv 文件。

回答by Thuat Nguyen

You can use my solution:

您可以使用我的解决方案:

public static void main(String[] args) {
    JSONObject jsonObj = new JSONObject(jsonArray);
    JSONArray docs = jsonObj.getJSONArray("results");
    File file = new File("C:/fromJSON2.csv");
    String csv = getDocs(docs);
    FileUtils.writeStringToFile(file, csv);
  }

  public static String getDocs(JSONArray ja) throws JSONException {
    String result = "";
    Map<String, Integer> map = new HashMap<>();
    for (int i = 0; i < ja.length(); i++) {
      JSONObject jo = ja.optJSONObject(i);
      if (jo != null) {
        getAllTopKeyAndValue(jo, map);
        if (i == 0) {
          result += keyOfMap2String(map) + "\n";
        }
        result += valueOfMap2String(map) + "\n";
      }
    }
    return result;
  }


  public static void getAllTopKeyAndValue(JSONObject jo, Map<String, Integer> map) {
    if (jo != null) {
      JSONArray names = jo.names();
      String string = "";
      List integers = new ArrayList<>();
      if (names != null) {
        for (int i = 0; i < names.length(); i++) {
          String name = names.getString(i);
          JSONObject object = jo.optJSONObject(name);
          if (object != null) {
            getAllTopKeyAndValue(object, map);
          } else {
            map.put(name, (Integer) jo.get(name));
          }
        }
      }
    }
  }

  public static String keyOfMap2String(Map<String, Integer> map) {
    String result = "";
    Iterator<Map.Entry<String, Integer>> iter = map.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry<String, Integer> entry = iter.next();
      result += entry.getKey();
      if (iter.hasNext()) {
        result += ",";
      }
    }
    return result;
  }

  public static String valueOfMap2String(Map<String, Integer> map) {
    String result = "";
    Iterator<Map.Entry<String, Integer>> iter = map.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry<String, Integer> entry = iter.next();
      result += entry.getValue();
      if (iter.hasNext()) {
        result += ",";
      }
    }
    return result;
  }