这是我的代码
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
public class Test {
public static void main(String[] args) throws IOException {
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createJsonGenerator(new File("test.json"), JsonEncoding.UTF8);
for(int i=0;i<4;i++){
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("name" , "test");
jGenerator.writeEndObject(); // }
jGenerator.writeRaw('\n'); // creates new line
}
jGenerator.close();
System.out.println("File Generated");
}
}
当我查看生成的文件后运行它,它在每个新记录之前有一个空格..有没有办法在生成文件时删除这个空间??
示例输出
{"name":"test"}
{"name":"test"}
{"name":"test"}
{"name":"test"}
答案 0 :(得分:4)
使用下一个PrettyPrinter
new MinimalPrettyPrinter("");
您的代码看起来像
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createJsonGenerator(new File("test.json"), JsonEncoding.UTF8);
jGenerator.setPrettyPrinter(new MinimalPrettyPrinter(""));
for(int i=0;i<4;i++)
{
jGenerator.writeStartObject();
jGenerator.writeStringField("name" , "test");
jGenerator.writeEndObject();
jGenerator.writeRaw('\n');
}
jGenerator.close();