0

I have a JSON Array that looks like this:

    {
        "Qty": "12",
        "Size": "XL",
        "Colour": "Blue",
        "InSale": "True"
    },
    {   "Qty": "13",
        "Size": "M",
        "Colour": "Green",
        "InSale": "False"}]

I want to convert this into a tab separated String. I am able to convert into comma separated string like this and able to write to a file:

String csvString = CDL.toString(ProductsJSONArray);
FileUtils.writeStringToFile(file, csvString);

How can I achieve it for tab separated String? This is the output I am expecting:

Qty Size    Color   InSale
12  XL  Blue    True
13  M   Green   False
Ruby
  • 368
  • 1
  • 9
  • possible duplicate to: https://stackoverflow.com/questions/7172158/converting-json-to-xls-csv-in-java – donvogel Feb 21 '23 at 07:18
  • But if the data values in json consist "," then even that will be replaced with tab. It will lead to incorrect data. – Ruby Feb 21 '23 at 07:36
  • @Ruby you are right - you need some JSON-parser to parse the input data, and a csv library for writing. There are lots of libraries for both topics, one example for a combination is in the linked question. – Hulk Feb 21 '23 at 07:46
  • @Ruby I assume you are currently using https://stleary.github.io/JSON-java/org/json/CDL.html? – Hulk Feb 21 '23 at 08:02
  • I'm afraid that library does not provide an option to choose a different delimiter. – Hulk Feb 21 '23 at 08:09
  • @Hulk CDL is specifically for comma, it doen't give us an option to change the delimiter. I'm not sure what other methods I can try – Ruby Feb 21 '23 at 10:01
  • @Ruby [this related question](https://stackoverflow.com/questions/13879967/good-and-effective-csv-tsv-reader-for-java) contains a few links to libraries that might be useful. – Hulk Feb 21 '23 at 10:09

1 Answers1

1

You'd probably want to pick a third party JSON parser library. You could use the jackson object mapper

ObjectMapper objectMapper = new ObjectMapper();
String json = "[{ \"Qty\":\"12\", ... }]";
ArrayNode array = objectMapper.readValue(json, ArrayNode.class);
Set<String> fieldNames = new LinkedHashSet<>();
for (JsonNode node : array) {
   // loop all nodes to get the unique set of fieldNames
   node.fieldNames().forEachRemaining(fieldNames::add);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println(fieldNames.stream().collect(Collectors.joining("\t"));
for (JsonNode node : array) {
   String csvRow = fieldNames.stream()
      .map(fieldName -> node.has(fieldName) ? node.get(fieldName).asText() : "")
      .collect(Collectors.joining("\t"))
   pw.println(csvRow);
}
String csv = sw.toString();
lance-java
  • 25,497
  • 4
  • 59
  • 101