我正在尝试将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);
}
}发布于 2015-02-11 16:30:03
看起来您可能正在覆盖每一行的value2。
value2= datavalue[1];编辑:你能让value2成为一个列表并添加到其中吗?
value2.add(datavalue[1]);EDIT2:在使用数组之前,您需要检查它的大小。
if (datavalue.length >= 2){
value2.add(datavalue[1]);
}发布于 2015-02-11 16:31:29
我建议您使用杰克逊高性能的JSON处理器。
来自http://jackson.codehaus.org/
下面是他们教程中的示例
最常见的用法是提取JSON的一部分,并从JSON中构建一个普通的旧Java对象("POJO")。所以让我们从这里开始。使用这样简单的2-property 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);使用opencsv处理在列中包含信息的文件,如csv I为该任务推荐的文件,这里是一个示例,用于5列中由“AC.26”分隔的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,这个问题在堆栈溢出中得到了解决。
发布于 2015-02-11 16:51:02
例外的原因可能是value2=datavlue1;
意味着在that循环的第一次执行期间,您试图将String数组中的秒元素(Datavalue1)分配给value2,而value2不是由then.So创建的--它提供了该异常。
https://stackoverflow.com/questions/28459298
复制相似问题