gpt4 book ai didi

java - java对象转json

转载 作者:行者123 更新时间:2023-11-29 05:11:07 25 4
gpt4 key购买 nike

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

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

提前致谢。

文件.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,并从中构造一个普通旧 Java 对象(“POJO”)。让我们从这里开始吧。使用像这样的简单的 2 属性 POJO:

//注意:也可以使用getters/setters;这里我们直接使用公共(public)字段:

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 实例,用于所有数据绑定(bind),所以让我们构建一个:

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 这样的列中包含信息的文件我建议为此任务使用 opencsv,这里是一个由“|”分隔的 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

关于java - java对象转json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28459298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com