我们这里使用fastjosn
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
_code:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import javax.sound.midi.Soundbank;
import java.io.*;
import java.util.List;
import java.util.Map;
/**
* @Author s.o.n.g
* @create 2022/8/30
*/
public class ReadLocalJsonFileDemo {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\Administrator\\Desktop\\XX.json");
readerMethod(file);
}
private static <error> void readerMethod(File file) throws IOException {
FileReader fileReader = new FileReader(file);
Reader reader = new InputStreamReader(new FileInputStream(file), "Utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
String jsonStr = sb.toString();
System.out.println(jsonStr);
//如果是json是非数组类型的情况使用下面的转化
try {
System.out.println(JSONObject.parseObject(jsonStr));
//这个地方可能会报错 看看是不是需要升级fastjson 或者 读取的json文件格式不对
}catch (Exception error){
System.out.println(error);
}
//如果是json是数组转对象 下面
/* JSONArray jsona =(JSONArray)JSONArray.parse(jsonStr);
System.out.println(jsona);
List<Map> list = JSONObject.parseArray(jsona.toJSONString(), Map.class);
System.out.println(list);
for(Map i:list){
System.out.println(i.get("id"));
}*/
}
}
注意:
json 的格式要正确
一般两种格式
一种是: String转JSONObject
这种格式 需要在最外层有一个{}括号 如果是一个对象的话不需要
一个以上需要 最外面加{}不然报错。
一种是:String转JSONArray
这种格式需