1

I am using the following code to read the CSV file and parse its data to JSON.

            File inputFile = new File("in.csv");
            File outputFile = new File("out.json");
            CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
            CsvMapper csvMapper = new CsvMapper();


            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
            mapper.writerWithDefaultPrettyPrinter().writeValue(outputFile, 
            csvMapper.readerFor(Map.class).with(csvSchema).readValues(inputFile).readAll());

This is working fine and giving me output as follow,

[
 {
  "Nutrient" : "Calories",
  "Amount" : " 289.00",
  "Unit" : " kcal"
}, {
  "Nutrient" : "Fat",
  "Amount" : " 17.35",
  "Unit" : " g"
}
]

But the required output is

{
{
  "Nutrient" : "Calories",
  "Amount" : " 289.00",
  "Unit" : " kcal"
}, {
  "Nutrient" : "Fat",
  "Amount" : " 17.35",
  "Unit" : " g"
}
}

Actually I need to read the JSONs files that I have converted from CSVs. Using the following code

             String content = Files.readString(filePath);
             JSONObject jsonObject1 = new JSONObject(content);
             HashMap yourHashMap1 = new Gson().fromJson(jsonObject1.toString(), HashMap.class);

But while I am trying to do it gives me this error.

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

Meanwhile json file should start with { instead of [ and similarly it should end on } instead ]. My goal is to remove this error.

Lily
  • 605
  • 3
  • 15
  • 31

1 Answers1

2

I think the result you are seeing is correct and that is the way JSON is supposed to be. JSON is a key value based format.


The output which you have pasted just means it is an array of json objects
[ { "Nutrient" : "Calories", "Amount" : " 289.00", "Unit" : " kcal" }, { "Nutrient" : "Fat", "Amount" : " 17.35", "Unit" : " g" } ]

The below JSON actually makes no sense, as there are no keys to the object. Even if you try to parse this kind of JSON with Jackson, it will throw an error Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name at [Source: (String)"{ . You can try this out


{ { "Nutrient" : "Calories", "Amount" : " 289.00", "Unit" : " kcal" }, { "Nutrient" : "Fat", "Amount" : " 17.35", "Unit" : " g" } }

The other option would be to consider each json object as a unique node with a distinct name like below, see the keyword set1 and set2
{ "set1": { "Nutrient" : "Calories", "Amount" : " 289.00", "Unit" : " kcal" }, "set2": { "Nutrient" : "Fat", "Amount" : " 17.35", "Unit" : " g" } }


For some reason if you really want to have {} instead of [] then just make a string operation and replace 1st "[" with "{" and last "]" with "}



Edited the answer to match the edited question: Now as we know your JSON is an array of JSON objects, you have to read it as JSONArray instead of JSONObject, also you can no more read it to a hashmap, it has to be a list, where each element in the list will be a JSONObject which has your data. Working code snippet is below

    String content = Files.readString(filePath);
    JSONArray jsonArray = new JSONArray(content);
    List<LinkedTreeMap> yourList = new Gson().fromJson(jsonArray.toString(), ArrayList.class);

    for(LinkedTreeMap l : yourList) {
        System.out.println(l.get("Amount"));
        System.out.println(l.get("Nutrient"));
        System.out.println(l.get("Unit"));
    }
Chandan
  • 640
  • 4
  • 10
  • Sir but I need it in HashMap. Your updated answer is giving me this error `Exception in thread "main" java.lang.IllegalArgumentException: The number of object passed must be even but was [1]` on line `IndexRequest indexRequest = new IndexRequest(index, TYPE).source(yourList);` – Lily May 04 '20 at 17:01
  • 1. Need complete stack trace of the error (this is a working code, so there shouldnt be any exceptions, can you confirm if your csv has a fixed schema ? fixed number of columns ?) 2. Directly, you cannot map this kind of JSON data to any hashmap, we have to make some modifications, Please let me know how you want to represent this data as hashmap ? what should be keys and what should be values ? Only then we can make a conclusion – Chandan May 04 '20 at 18:37