我有一些代码,其中包含描述符列表,并使用GSON库将它们写入不同的JSON文件。我现在正在尝试将该库更改为Jackson。我不是杰克逊专家,所以我正在寻求帮助。这是我使用GSON时的代码:
描述符类:
public class Descriptor {
@SerializedName("BatchName")
private String batchName;
@SerializedName("Metadata")
private Metadata metadata;
@SerializedName("SampleInfo")
private SampleInfoJsonModel sampleInfo;
@SerializedName("Files")
private List<String> files;
@SerializedName("ClientData")
private ClientData clientData;
@SerializedName("CaseName")
private String caseName;
public Descriptor() {
this.metadata = new Metadata();
this.sampleInfo = new SampleInfoJsonModel();
this.files = new ArrayList<String>();
this.clientData = new ClientData();
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public SampleInfoJsonModel getSampleInfo() {
return sampleInfo;
}
public void setSampleInfo(SampleInfoJsonModel sampleInfo) {
this.sampleInfo = sampleInfo;
}
public List<String> getFiles() {
return files;
}
public void setFiles(List<String> files) {
this.files = files;
}
public ClientData getClientData() {
return clientData;
}
public void setClientData(ClientData clientData) {
this.clientData = clientData;
}
public String getCaseName() {
return caseName;
}
public void setCaseName(String caseName) {
this.caseName = caseName;
}
public ClientData getClientDataNoCountryCodes() {
// TODO Auto-generated method stub
return null ;
}
}
我的写入JSON文件功能:
public static void writeJsonFile(List<Descriptor> descriptors) {
try {
for(Descriptor descriptor : descriptors) {
BufferedWriter buffWrite = new BufferedWriter(new FileWriter("descriptor_"+descriptor.getCaseName()+".json"));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
buffWrite.write(gson.toJson(descriptor));
buffWrite.close();
}
}
catch (IOException ioe) {
System.err.println("Error while writing to json file in writeJsonFile: ");
ioe.printStackTrace();
}
}
这是我在杰克逊写的东西:
BufferedWriter buffWrite = new BufferedWriter(new FileWriter("descriptor_"+descriptor.getCaseName()+".json"));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
buffWrite.write(mapper.writeValueAsString(descriptor));
这等同于下面GSON中的代码吗?
BufferedWriter buffWrite = new BufferedWriter(new FileWriter("descriptor_"+descriptor.getCaseName()+".json"));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
buffWrite.write(gson.toJson(descriptor));
buffWrite.close();
答案 0 :(得分:1)
我认为您正在寻找为对象生成漂亮的JSON输出并将其写入文件的方法。
您必须确保在对象属性上使用@SerializedName
的{{1}}杰克逊等效注解。
此外,您还可以使用以下代码通过杰克逊ObjectMapper来美化JSON
@JsonProperty
请注意,设置mapper.writerWithDefaultPrettyPrinter().writeValueAsString( descriptorObj )
也将有助于您完成已经在想的事情。
Files
API对于与文件相关的操作也非常有用。
我希望这会有所帮助!