[英]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中的這個問題中得到了解決
看起來你可能會為每一行覆蓋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.