读取json格式文件,将其格式化输出
程序员文章站
2022-05-28 15:25:44
...
使用fastjson
@Test
public void testdsa() throws IOException {
/*JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("1", "222");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("1111", "44444");
jsonArray.add(jsonObject);
jsonArray.add(jsonObject2);*/
BufferedInputStream bis = null;
StringBuilder sb = new StringBuilder();
byte[] b = new byte[1024 * 1024];
try {
bis = new BufferedInputStream(new FileInputStream(new File("a - 副本.txt")));
int len = -1;
while ((len = bis.read(b)) != -1) {
sb.append(new String(b, 0, len));
}
System.out.println("jie");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
}
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("out01.txt"))));
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
JSONObject content = jsonObject.getJSONObject("content");
if (content != null) {
JSONArray etOutputs = content.getJSONArray("etOutputs");
for (int i = 0; i < etOutputs.size(); i++) {
JSONObject obj = etOutputs.getJSONObject(i);
String pretty = JSON.toJSONString(obj, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
bw.write(pretty);
bw.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bw != null) {
bw.close();
}
}
}