将java对象转换为json

时间:2015-02-11 16:24:09

标签: java 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);
    }
}

3 个答案:

答案 0 :(得分:3)

我建议你使用 杰克逊 高性能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

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

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

中的这个问题中得到了解决

How do you return a JSON object from a Java Servlet

答案 1 :(得分:0)

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

value2= datavalue[1];

编辑:您可以将value2设为List并添加到其中。

value2.add(datavalue[1]);

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

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

答案 2 :(得分:0)

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

表示在你第一次执行while循环时,你试图将String数组中的秒元素(datavalue [1])分配给value2,这不是由那时创建的。所以它给出了该异常。