Home > Software engineering >  Java8 convert csv to json object
Java8 convert csv to json object

Time:11-05

i am comparing two json objects, one of them get request and other input from csv file --- for the csv to json logic -- following code,

csv file looks like this ---- the csv file looks like this -

sw product,sw product module,technology
Product 1,Module 1,REGULAR
Product 1,Module 2,SPRING CLOUD
Product 2,Module 1,REGULAR
Product 2,Module 3,REGULAR

JAVA CODE

package com.beandependencyinjection.configurationbeans.service;

public class ConvertCsvToJson {
    public static void main(String[] args)  {

        String filesss = "C:\products\\swproduct.csv";
        ConvertCsvToJson result = new ConvertCsvToJson();

        System.out.println(result.CSVtoJSON(filesss));


    }

    public String CSVtoJSON(String output) {

            String[] lines = output.split(",");

            StringBuilder builder = new StringBuilder();
            builder.append('[');
            String[] headers = new String[0];

            //CSV TO JSON
            for (int i = 0; i < lines.length; i  ) {
                String[] values = lines[i].replaceAll(",", "").split("۞");

                if (i == 0) //INDEX LIST
                {
                    headers = values;
                } else {
                    builder.append('{');
                    for (int j = 0; j < values.length && j < headers.length; j  ) {

                        String jsonvalue = "\""   headers[j]   "\":\""   values[j]   "\"";
                        if (j != values.length - 1) { //if not last value of values...
                            jsonvalue  = ',';
                        }
                        builder.append(jsonvalue);
                    }
                    builder.append('}');
                    if (i != lines.length - 1) {
                        builder.append(',');
                    }
                }
            }
            builder.append(']');
            output = builder.toString();

            return output;
        }
}

but its not working -- any help appreciated

CodePudding user response:

Your implementation looks very low level. Instead, you can do it like this and make use of the ObjectMapper class.

Pattern pattern = Pattern.compile(",");
try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) {
    List < Product > products = in .lines().skip(1).map(line - > {
        String[] fields = pattern.split(line);
        return new Product(...use values in fields to create product...);
    }).collect(Collectors.toList());
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.writeValue(System.out, products);
}

More details are available here

CodePudding user response:

Instead of using your own logic to parse CSV and convert it to JSON, you can take use of some libraries.

For Reading CSV you can use opencsv, this gives you option to directly read a CSV to a Map

Map<String, String> values = new CSVReaderHeaderAware(new FileReader("yourfile.csv")).readMap();

Post this you can use Jackon to convert map to a JSON.

ObjectMapper objectMapper = new ObjectMapper();
mapper.writeValueAsString(map);

There are many different frameworks available for Reading CSV file and converting text to JSON, you can explore.

  • Related