繁体   English   中英

将java对象转换为json

[英]converting java object to json

我试图将java对象转换为json。 我有一个java类,它从文本文件中读取特定的列。 我想以json格式存储该读取列。

这是我的代码。 我不知道我哪里错了。

提前致谢。

File.java

public class File {

    public File(String filename)
            throws IOException {
        filename = readWordsFromFile("c:/cbir-2/sample/aol.txt");
    }

    public String value2;

    public String readWordsFromFile(String filename)
            throws IOException {
        filename = "c:/cbir-2/sample/aol.txt";
        // Creating a buffered reader to read the file
        BufferedReader bReader = new BufferedReader(new FileReader(filename));
        String line;
        //Looping the read block until all lines in the file are read.

        while ((line = bReader.readLine()) != null) {
            // Splitting the content of tabbed separated line
            String datavalue[] = line.split("\t");
            value2 = datavalue[1];
            // System.out.println(value2);
        }

        bReader.close();

        return "File [ list=" + value2 + "]";
    }
}

GsonExample.java

import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args)
            throws IOException {
        File obj = new File("c:/cbir-2/sample/aol.txt");
        Gson gson = new Gson();
        // convert java object to JSON format,
        // and returned as JSON formatted string
        String json = gson.toJson(obj);

        try {
            //write converted json data to a file named "file.json"
            FileWriter writer = new FileWriter("c:/file.json");
            writer.write(json);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(json);
    }
}

我建议你使用Jackson高性能JSON处理器。

来自http://jackson.codehaus.org/

这是他们教程中的示例

最常见的用法是使用JSON,并从中构造一个Plain Old Java Object(“POJO”)。 那么让我们从那里开始。 简单的2属性POJO像这样:

//注意:也可以使用getter / setter; 这里我们直接使用公共字段:

public class MyValue {
  public String name;
  public int age;
  // NOTE: if using getters/setters, can keep fields `protected` or `private`
}

我们需要一个com.fasterxml.jackson.databind.ObjectMapper实例,用于所有数据绑定,所以让我们构造一个:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse

默认实例适合我们使用 - 稍后我们将了解如何在必要时配置映射器实例。 用法很简单:

MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
// or:
value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// or:
value = mapper.readValue("{\"name\":\"Bob\", \"age\":13}", MyValue.class);

如果我们想写JSON,我们会做相反的事情:

mapper.writeValue(new File("result.json"), myResultObject);
// or:
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// or:
String jsonString = mapper.writeValueAsString(myResultObject);

处理一个文件,其中包含像csv这样的列的信息我为这个任务使用openlcv这里是一个例子,用于5列中用'|'分隔的信息

import com.opencsv.CSVReader;
import pagos.vo.UserTransfer;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by anquegi on
 */
public class CSVProcessor {

    public List<String[]> csvdata = new ArrayList<String[]>();

    public CSVProcessor(File CSVfile) {

        CSVReader reader = null;

        try {
            reader = new CSVReader(new FileReader(CSVfile),'|');
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Logger.error("Cannot read CSV: FileNotFoundException");
        }
        String[] nextLine;
        if (reader != null) {
            try {
                while ((nextLine = reader.readNext()) != null) {
                    this.csvdata.add(nextLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
                Logger.error("Cannot read CSV: IOException");
            }
        }


    }



    public List<TransfersResult> extractTransfers() {

        List<TransfersResult> transfersResults = new ArrayList<>();


        for(String [] csvline: this.csvdata ){

            if(csvline.length >= 5){
            TransfersResult transfersResult = new TransfersResult(csvline[0]
                    ,csvline[1],csvline[2],csvline[3],csvline[4]);

            // here transfersResult is a pojo java object
            }

        }

        return transfersResults;

    }

}

并且为了从servlet返回一个json,这在stackoverflow中的这个问题中得到了解决

如何从Java Servlet返回JSON对象

看起来你可能会为每一行覆盖value2。

value2= datavalue[1];

编辑:你可以使value2成为一个列表并添加到它。

value2.add(datavalue[1]);

EDIT2:您需要在使用之前检查阵列的大小。

if (datavalue.length >= 2){
    value2.add(datavalue[1]);
}

异常的原因可能是value2 = datavlue [1];

你在第一次执行while循环时意味着你试图将String数组中的秒元素(datavalue [1])赋值给value2,而不是由那时创建的。所以它给出了这个异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM