簡體   English   中英

將DTO轉換為JSON

[英]convert DTO to JSON

我已經創建了一個類,用於將csv文件轉換為dto然后轉換為ojson結構,但是當我轉換為json時,我得到csv中的最后一行。

這是我的代碼

public class TermParsing {

    private static final Logger log = Logger.getLogger(TermParsing.class.getName());
    Properties prop = new Properties();
    String data;
    //creating object for the dto class
    TermParsingDTO term = new TermParsingDTO();
    CsvReader read;
    JSONObject json = new JSONObject();
    HashMap hmap=new HashMap();

    //method to parse the csv file    
    void changeFileType() throws IOException {
        try {
            //to get the properties file from the source
            FileReader file = new FileReader("./config.txt");
            //loading the properties file
            prop.load(file);
            data = prop.getProperty("File");
            String path = prop.getProperty("Path");
            //to export the log message to the target
            FileHandler fh = new FileHandler(path);
            log.addHandler(fh);
            //to format the log messages
            SimpleFormatter format = new SimpleFormatter();
            fh.setFormatter(format);
            log.warning("FileNotFoundException may occur");
            //reading the input csv file
            read = new CsvReader(data);
            read.readHeaders();
            //to obtain the values from csv file 
            while (read.readRecord()) {
                term.setTerm_Name(Arrays.asList(read.get("Term Name")));
                term.setParent_category(Arrays.asList(read.get("Parent Category")));
                term.setShort_description(Arrays.asList(read.get("Short Description")));
                term.setLong_description(Arrays.asList(read.get("Long Description")));
                term.setStatus(Arrays.asList(read.get("Status")));
            }                
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TermParsing.class.getName()).log(Level.SEVERE, "FileNotFoundException", ex);
        }
    }

在這個方法中,我的json結構僅為單個值創建

void convertToJson() throws IOException {            
    ObjectMapper map = null;
    String jsonInString;
    map = new ObjectMapper();
    jsonInString = map.writerWithDefaultPrettyPrinter().writeValueAsString(term);
    System.out.println(jsonInString);
}

你不應該獨立閱讀所有行嗎?

TermParsingDTO term = new TermParsingDTO();

這應該是:

List<TermParsingDTO> terms = new ArrayList<>();

在你的循環結束時:

terms.add(term);

然后,您的所有記錄都將在您的列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM