2

I have a CSV file which has 10 columns and multiple rows. I want to store each row in a JSON object. For example the file would look like below :

Name, Age, Address..........and other columns
ABCD, 23 , HOME.............and other columns

So I want it to be stored in a JSON object as {"Name":"ABC" ,"Age":"23", "Address":"HOME"}

Now, since there will be multiple rows, how do I create an array of JSON objects and store each row in an object? How do I retrieve or print each row too from the JSON objects?

Thanks a lot.

Nishant
  • 54,584
  • 13
  • 112
  • 127
user1232325
  • 21
  • 1
  • 1
  • 2

2 Answers2

5

JSON Object should create something like this:-

{'UserDetails': [{'Name':'ABC', 'Age':'44', 'Address':'HOME'}, 
                 {'Name':'DEF','Age':'23', 'Address':'HOME'}]
                 .....
                 .....
}

To Retrieve:-

JSONObject userDet = new JSONObject(user_info);
JSONArray userDetJson = userDet.getJSONArray("UserDetails");

Refer some more information Convert a JSON string to object in Java?, Creating & Parsing JSON data with Java Servlet/Struts/JSP and JSON-lib: Snippets

Community
  • 1
  • 1
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
1

Create object which will hold 10 parameters

public class LineObject implements Serializable {
   private String name;
   private int age;
   private String address;
   //...
   // get,set,equals,hashcode
}

then parse CSV file and each line save to LineObject. By parsing whole file you'll get List<LineObject>. Then serialize this to JSON using e.g. Jackson JSON processor.

To get object from JSON, use again Jackson JSON processor for deserialization.

kurochenko
  • 1,214
  • 3
  • 19
  • 43