package com.ht.projectdemo.common;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.Map;
public class LocalJSONFileUtil {
public static Object getJSONByKey(String filepath, String key){
String text = LocalJSONFileUtil.getFileText(filepath);
JSONObject object = new JSONObject();
if (StringUtils.isNoneBlank(text)){
object = parseObject(text);
}
return object.get(key);
}
public static JSONObject parseObject(String text) {
return JSONObject.parseObject(text);
}
public static String getFileText(String filepath){
StringBuffer sb = new StringBuffer();
try{
ClassPathResource classPathResource = new ClassPathResource(filepath);
Reader reader = new InputStreamReader(classPathResource.getInputStream());
int ch = 0;
while ((ch = reader.read())!=-1){
sb.append((char)ch);
}
}catch (Exception e) {
e.printStackTrace();
}
return sb.toString().replaceAll("\r\n","");
}
}
class Text{
public static void main(String[] args) {
System.out.println("获取json文本,也可以获取txt文本");
String textJOSN = LocalJSONFileUtil.getFileText("templates/localJSON.json");
System.out.println(textJOSN);
String txt = LocalJSONFileUtil.getFileText("templates/localJSON.txt");
System.out.println(txt);
System.out.println("=============通过key获取对象=================");
String key2 = (String) LocalJSONFileUtil.getJSONByKey("templates/localJSON.json","key2");
System.out.println("key2:"+key2);
List<Map<String,Object>> key3 = (List<Map<String, Object>>) LocalJSONFileUtil.getJSONByKey("templates/localJSON.json","key3");
System.out.println(key3);
Map<String,Object> key4 = (Map<String, Object>) LocalJSONFileUtil.getJSONByKey("templates/localJSON.json","key4");
System.out.println(key4);
System.out.println("=========获取整体json对象=============");
Map<String,Object> objectMap = LocalJSONFileUtil.parseObject(LocalJSONFileUtil.getFileText("templates/localJSON.json"));
System.out.println(objectMap.get("key1"));
Map<String,Object> objectMap2 = JSONObject.parseObject(LocalJSONFileUtil.getFileText("templates/localJSON.json"));
System.out.println(objectMap2.get("key1"));
System.out.println("向文本内写入值,一般工作中没有这个需求,思路也很简单,封装个方法,参数为,路径,key,value, 通过路径读取JSON到程序,通过map的put方法向json中put值,最后将数据再次写入到JSON文件内就行了");
}
}
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.39</version>
</dependency>
<!-- common -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
|