-1

Example to convert csv format to Json in android. I found a solution in Converting an CSV file to a JSON object in Java but not working or I am missing anything.

Thanks in advance.

  package com.example.readfilefromsdcard;

 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.Reader;
 import java.util.List;

 import org.codehaus.jackson.map.ObjectMapper;

 import com.opencsv.bean.ColumnPositionMappingStrategy;
 import com.opencsv.bean.CsvToBean;
 import com.opencsv.bean.HeaderColumnNameMappingStrategy;
 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.Toast;

  public class MainActivity extends Activity {

Button btnWriteSDFile;
Button btnReadSDFile;
String path = "/sdcard/mydocs/test.csv";


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
    btnReadSDFile.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            try {
                 ConvertCsvToJson(path,"TestJavaBeans");
                // ConvertCsvToJson1(path);
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

public void ConvertCsvToJson(String path, String clsName) throws IOException, ClassNotFoundException {

    String pathToCsvFile = path;
    String javaBeanClassName = "" + clsName;
    final File file = new File(pathToCsvFile);
    if (!file.exists()) {
        System.out.println("The file you specified does not exist. path=" + pathToCsvFile);
    }
    Class<?> type = null;
    try {
        type = Class.forName(javaBeanClassName);
    } catch (ClassNotFoundException e) {
        System.out.println("The java bean you specified does not exist. className=" + javaBeanClassName);
    }

    HeaderColumnNameMappingStrategy<TestJavaBeans> strat = new HeaderColumnNameMappingStrategy<TestJavaBeans>();
    //strat.setType(type);
    CsvToBean<TestJavaBeans> csv = new CsvToBean<TestJavaBeans>();
    List<TestJavaBeans> list = csv.parse(strat, new InputStreamReader(new FileInputStream(file)));
    System.out.println(new ObjectMapper().writeValueAsString(list));

}

public void ConvertCsvToJson1(String path) throws IOException, ClassNotFoundException {

    final ColumnPositionMappingStrategy<TestJavaBeans > strategy = new ColumnPositionMappingStrategy<TestJavaBeans>();
    strategy.setType(TestJavaBeans .class);
    strategy.setColumnMapping(new String[] { "name", "id", });
    final CsvToBean<TestJavaBeans > csvToBean = new CsvToBean<TestJavaBeans >();
    final List<TestJavaBeans > beanExamples;
    try {
        final Reader reader = new FileReader(path);
        beanExamples = csvToBean.parse(strategy, reader);
        System.out.println(new       ObjectMapper().writeValueAsString(beanExamples));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

}

  package com.example.readfilefromsdcard;

 public class TestJavaBeans {
       private String name;
       private String id;
       public String getName() {
         return name;
}
public void setName(String name) {
    this.name = name;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}

}

Referenced libraries : jackson-all-1.9.0.jar and opencsv-3.3.jar

log: Could not find method java.beans.Introspector.getBeanInfo, referenced from method com.opencsv.bean.HeaderColumnNameMappingStrategy.loadDescriptors

Community
  • 1
  • 1
Bhola Nath Mahto
  • 484
  • 5
  • 18

3 Answers3

1

There's really no universal "convert": JSON is a heirarchical structure, while CSV is flat. You need to model the JSON object and map fields from the CSV to the JSON object one at a time. It's more a logic problem rather than a coding one.

Endareth
  • 492
  • 3
  • 15
1

I would suggest this approach

create a Java "wrapper" class that has a class variable List<TestJavaBeans> list

Then use Jackson to convert this "wrapper" to json

Hector
  • 4,016
  • 21
  • 112
  • 211
0

The link which i preferred for converting csv to json is as follows:

https://github.com/cparker15/csv-to-json?files=1

Rajan Bhavsar
  • 1,977
  • 11
  • 25