user1232325
user1232325

Reputation: 21

Create an array of JSON Objects in Java

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.

Upvotes: 2

Views: 12816

Answers (2)

Siva Charan
Siva Charan

Reputation: 18064

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

Upvotes: 5

kurochenko
kurochenko

Reputation: 1254

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.

Upvotes: 1

Related Questions