Java对Json文件的读取与修改
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
1:操作步骤
将Json文件读取为Json字符串--->根据JsonPath修改对应Path的value值---->格式化Json字符串---->将格式化后的Json字符串写入指定Json文件中
2:代码目录结构
|——cn.Demo.ReadJson //Package
|————FileUtils.java //将Json文件读取为字符串 将Json字符串写入文件
|————FormatJsonUtlis.java //格式化Json字符串
|————RwJsonFileUtils.java //读写Json
|————Demo.json //演示Demo Json文件
3:导入Maven依赖
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.3.0</version>
</dependency>
4:代码实现
FileUtils.java
/**
* @author Anndy
*
* */
package cn.Demo.ReadJson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class FileUtils {
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static String readJsonData(String pactFile){
// 读取文件数据
//System.out.println("读取文件数据util");
StringBuffer strbuffer = new StringBuffer();
File myFile = new File(pactFile);//"D:"+File.separatorChar+"DStores.json"
if (!myFile.exists()) {
System.err.println("Can't Find " + pactFile);
}
try {
FileInputStream fis = new FileInputStream(pactFile);
InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
BufferedReader in = new BufferedReader(inputStreamReader);
String str;
while ((str = in.readLine()) != null) {
strbuffer.append(str); //new String(str,"UTF-8")
}
in.close();
} catch (IOException e) {
e.getStackTrace();
}
//System.out.println("读取文件结束util");
return strbuffer.toString();
}
// 把json格式的字符串写到文件
public static boolean writeFile(String filePath, String sets) {
FileWriter fw;
try {
fw = new FileWriter(filePath);
PrintWriter out = new PrintWriter(fw);
out.write(sets);
out.println();
fw.close();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
FormatJsonUtlis.java
package cn.Demo.ReadJson;
/**
* 格式化输入工具类
*
*/
public class FormatJsonUtlis {
/**
* 格式化
*
* @author Anndy
*/
public static String formatJson(String jsonStr) {
if (null == jsonStr || "".equals(jsonStr))
return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
boolean isInQuotationMarks = false;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\'){
isInQuotationMarks = !isInQuotationMarks;
}
sb.append(current);
break;
case '{':
case '[':
sb.append(current);
if (!isInQuotationMarks) {
sb.append('\n');
indent++;
addIndentBlank(sb, indent);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb.append('\n');
indent--;
addIndentBlank(sb, indent);
}
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\' && !isInQuotationMarks) {
sb.append('\n');
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
}
return sb.toString();
}
/**
* 添加space
*
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append('\t');
}
}
}
RwJsonFileUtils.java
package cn.Demo.ReadJson;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
public class RwJsonFileUtils{
public static void main(String[] args) {
String filePath = "G:\\workspace1\\ReadJson\\src\\main\\java\\cn\\Demo\\ReadJson\\Demo.json";
//将Json文件读取为字符串
String json = FileUtils.readJsonData("G:\\workspace1\\ReadJson\\src\\main\\java\\cn\\Demo\\ReadJson\\Demo.json");
//修改Json的value
DocumentContext context = JsonPath.parse(json);
JsonPath path = JsonPath.compile("$.result.records[0].name");
context.set(path, "修改成功了");
String changedJson = context.jsonString();
//将json字符串格式化 并写入制定文件
FileUtils.writeFile(filePath, FormatJsonUtlis.formatJson(changedJson));
String read = (String)JsonPath.read(changedJson, "$.result.records[1].mobile");
System.out.println(read.toString());
}
}
Demo.json
{
"action":"/interface.service/xxx/queryBlackUserData",
"all":"1",
"result":{
"count":2,
"tenant_count":2,
"records":[
{
"name":"修改成功了",
"pid":"500234199212121212",
"mobile":"18623456789",
"applied_at":"3",
"confirmed_at":"5",
"confirm_type":"overdue",
"loan_type":1,
"test":"mytest",
"all":"2"
},
{
"name":"李四",
"pid":"500234199299999999",
"mobile":"13098765432",
"applied_at":"1",
"confirmed_at":"",
"confirm_type":"overdue",
"loan_type":3,
"all":"3"
},
{
"name":"王五",
"pid":"50023415464654659",
"mobile":"1706454894",
"applied_at":"-1",
"confirmed_at":"",
"confirm_type":"overdue",
"loan_type":3
}
],
"all":"4"
},
"code":200,
"subtime":"1480495123550",
"status":"success",
"ok":3
}
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
4 个月前
8c391e04
6 个月前
更多推荐
已为社区贡献3条内容
所有评论(0)