版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xyy1028/article/details/81098159
解析JSON常用jar包
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
示例代码
1.读取.json文件中的内容
将文件中的内容以字符串的形式读出,用了org.apache.commons.io的jar包
String str= FileUtils.readFileToString(file, "UTF-8");
2.将json字符串转换成map
利用map,com.alibaba.fastjson;
Map jsonMap = JSON.parseObject(str);
3.将map转换成json对象格式,将json对象转换为字符串
利用org.json
JSONObject json =new JSONObject(jsonMap);
String jsonString = json.toString();
代码示例
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import java.io.*;
import java.util.Map;
public class JsonTest {
public static void main(String[] args) {
File files = new File("D:\\jsonTest");
String[] fileName = files.list();
for (int i = 0; i < fileName.length; i++) {
String path = "D:\\jsonTest\\" + fileName[i];
File file = new File(path);
try {
//将文件中的内容以字符串形式读出,org.apache.commons.io;
String str= FileUtils.readFileToString(file, "UTF-8");
//将json字符串转成map,com.alibaba.fastjson;
Map jsonMap = JSON.parseObject(str);
jsonMap.put("age",25);
//将map转换成json对象格式,org.json;
JSONObject json =new JSONObject(jsonMap);
String jsonString = json.toString();
String newPath = "D:\\jsonTest2\\" +fileName[i];
File newfile = new File(newPath);
newfile.createNewFile();
Writer write = new OutputStreamWriter(new FileOutputStream(newfile), "UTF-8");
write.write(jsonString);
write.flush();
write.close();
String name = fileName[i];
String headName = name.substring(name.lastIndexOf('\\') + 1, name.indexOf('.'));
String fullPath = "D:\\jsontxt\\" +headName+".txt";
File txtfile = new File(fullPath);
txtfile.createNewFile();
FileWriter out=new FileWriter (txtfile);
BufferedWriter bw= new BufferedWriter(out);
Map<String,String> hehe = jsonMap;
String line1Param = hehe.getOrDefault("order1","").toString();
String line2Param = hehe.getOrDefault("order2","").toString();
String line3Param = hehe.getOrDefault("order3","").toString();
String line4Param = hehe.getOrDefault("order4","").toString();
bw.write(line1Param);
//BufferedWriter提供的换行
bw.newLine();
bw.write(line2Param);
bw.newLine();
bw.write(line3Param);
bw.newLine();
bw.write(line4Param);
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}