gpt4 book ai didi

java - 漂亮的输出总是插入 "\r\n"

转载 作者:行者123 更新时间:2023-12-01 09:32:14 25 4
gpt4 key购买 nike

我正在开发一个费用计算器。之前,我有一个有效的 XML 输出,但没有打印换行符。我认为有些事情搞砸了,也许编辑器没有将换行符视为换行符,不知道。

但是当我节省开支时,我得到了一个非常丑陋的输出:

"[ {\r\n\"标题\":\"2\",\r\n\"类别\":\"[无]\",\r\n\"句号\":\"年份\",\r\n\"值\":\"2\"\r\n}, {\r\n\"标题\":\"3\",\r\n\“类别\”:\“[无]\”,\r\n\“期间\”:\“年份\”,\r\n\“值\”:\“3\”\r\n } ]"

如果我查看控制台(在那里进行打印),我会得到我想要的:

[ {
“标题”:“2”,
"类别": "[无]",
“期间”:“年份”,
“值”:“2”
}, {
“标题”:“3”,
"类别": "[无]",
“期间”:“年份”,
“值”:“3”
}]

目前,我的代码非常简单:

ObservableList<Expense> expenseList  = FXCollections.observableArrayList();
//The list gets edited by a TableView.
final ObjectMapper mapper = new ObjectMapper();
final String s = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(expenseList);
FileOutputStream fos = new FileOutputStream(path);
OutputStreamWriter outputFile = new OutputStreamWriter(fos, Charset.forName("UTF8"));

mapper.writeValue(outputFile, s);

这就是实体类的样子:

public class Expense {
private StringProperty title = new SimpleStringProperty();
private StringProperty category = new SimpleStringProperty();
private StringProperty period = new SimpleStringProperty();
private StringProperty value = new SimpleStringProperty();

public void setTitle(String title) {
this.title.set(title);
}

public void setCategory(String category) {
this.category.set(category);
}

public void setPeriod(String period) {
this.period.set(period);
}

public void setValue(String value) {
this.value.set(value);
}

public Expense() {} //Default constructor is needed for XML-handling

public Expense(String title, String value, String period, String category) {
this.title = new SimpleStringProperty(title);
this.value = new SimpleStringProperty(value);
this.period = new SimpleStringProperty(period);
this.category = new SimpleStringProperty(category);
}

public String getTitle() {
return this.title.get();
}

public String getCategory() {
return this.category.get();
}

public String getPeriod() {
return this.period.get();
}

public String getValue() {
return this.value.get();
}

public StringProperty titleProperty() {
return this.title;
}

public StringProperty categoryProperty() {
return this.category;
}

public StringProperty periodProperty() {
return this.period;
}

public StringProperty valueProperty() {
return this.value;
}
}

我尝试获取列表中的每个字符串并将其转换为 json 字符串 -> 将其连接到我打印出来的一个大字符串。但结果相同。

最佳答案

这行代码的作用

mapper.writeValue(outputFile, s);

获取一个字符串并将其作为值写入 JSON 消息中。如果该字符串已经包含特殊字符,则必须将它们转义。

您最想要的可能是

 try (FileOutputStream fos = new FileOutputStream(path);
OutputStreamWriter outputFile = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
outputFile .write(s); // just write the String as it is
}

关于java - 漂亮的输出总是插入 "\r\n",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314750/

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