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?

1
  • Create the Array and Map objects that represent the structure, then serialize them into JSON. Commented Mar 22, 2013 at 21:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

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
I believe the yourReader is the inputFileReader.
yeah got it thanks, also is there any documentation for using Jackson to covert javaBean to JSON? Thanks again.
This looks like a nice tutorial, but I haven't had a chance to go through it yet. mkyong.com/java/how-to-convert-java-object-to-from-json-jackson
If my answer was helpful, can you up vote it and/or select it as the correct answer? Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.