json数据的读取
import java.io.*;
import org.json.JSONObject;
import org.json.JSONArray;
public class Text {
public static void main(String[] args) throws IOException {
JSONArray jsonArray=new JSONArray();//创建JSONArray对象
File file=new File("Test.json");
if(!file.exists()){
System.out.println("未找到文件");
}
FileInputStream fileInputStream=new FileInputStream(file);//创建FileInputStream对象
InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream,"utf-8");//创建InputStreamReader对象
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);//创建字符输入流
String Js ="";
String Line = null;
while ((Line = bufferedReader.readLine()) != null) {
Js += Line;
}
JSONArray WE=new JSONArray(Js);//用读取到的字符串实例化JSONArray数组
for(int j=0;j<WE.length();j++)
{
JSONObject we = WE.getJSONObject(j);//将JSONArray中的json数据赋值给jsonobject对象
System.out.println(we.toString());//以字符串形式输出jsonobject对象
}
}
}
以下是json文件样例
[{
"Goal":98,
"Num":10,
"age":21
},
{
"Goal":75,
"Num":89,
"age":23
},
{
"Goal":80,
"Num":23,
"age":24
},
{
"Goal":100,
"Num":46,
"age":18
},
{
"Goal":60,
"Num":54,
"age":25
},
{
"Goal":73,
"Num":20,
"age":23
},
{
"Goal":82,
"Num":89,
"age":20
},
{
"Goal":76,
"Num":10,
"age":21
},
{
"Goal":83,
"Num":50,
"age":18
}]
以下是控制台输出情况
关于json数据的存储详见java中将简单的json数据写入文件