4

I've a csv file something similar to this

"name.firstName","name.givenName","name.DisplayName","phone.type","phone.value"
"john","maverick","John Maverick","mobile","123-123-123"
"jim","lasher","Jim Lasher","mobile","123-123-123"

I want to convert the 2nd and 3rd row into JSON objects.Using the first row as Header. So the result will be

[
{  
"name": {
    "firstName": "john",
    "givenName": "maverick",
    "DisplayName": "John Maverick"
},
"phone": {
    "type": "mobile",
    "value": "123-123-123"
}
},
{
"name": {
    "firstName": "john",
    "givenName": "maverick",
    "DisplayName": "John Maverick"
},
"phone": {
    "type": "mobile",
    "value": "123-123-123"
}
]

Any idea how to achieve this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
R Syed
  • 1,043
  • 5
  • 14
  • 22

1 Answers1

2

Here is a Java library that may help you. http://www.jonathanhfisher.co.uk/playpen/csv2json/index.htm

Here is a JavaScript library that may or may not be useful to you. http://www.cparker15.com/code/utilities/csv-to-json/

And finally, here is a past answer that may be useful. I like the OpenCSV solution. However, instead of JAXB, you could use Jackson. Converting an CSV file to a JSON object in Java

Community
  • 1
  • 1
Rob Breidecker
  • 604
  • 1
  • 7
  • 12
  • Thanks for the answer, in this third solution, the example code which is used is ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy(); strat.setType(YourOrderBean.class); String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean strat.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); List list = csv.parse(strat, yourReader); what exactly is yourReader here, and how do I input values to bind with bean? Thanks – R Syed Mar 22 '13 at 22:27
  • I believe the yourReader is the inputFileReader. – Rob Breidecker Mar 22 '13 at 22:39
  • yeah got it thanks, also is there any documentation for using Jackson to covert javaBean to JSON? Thanks again. – R Syed Mar 22 '13 at 23:10
  • This looks like a nice tutorial, but I haven't had a chance to go through it yet. http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ – Rob Breidecker Mar 22 '13 at 23:16
  • If my answer was helpful, can you up vote it and/or select it as the correct answer? Thanks! – Rob Breidecker Mar 23 '13 at 16:51
  • Thanks for the answer @robbr. I'm stuck in another problem here, when I map csv to JavaBean, for the attributes of my bean object not present in the csv, they are being assigned to null. I want to map only the values present in csvHeader to the attributes of my bean object. Can you tell me a way to do this? I've created a seperate question for this over here. http://stackoverflow.com/questions/15596438/csv-to-bean-excluding-the-values-not-included-in-csv-header-java – R Syed Mar 24 '13 at 08:23