1、创建JSON.txt文件
{
"name": "小王",
"age": 23,
"sex": "男"
}
2、创建Person对象
@Data
public class Person implements Serializable {
private static final long serialVersionUID = -348549485910717452L;
private String name;
private String sex;
private Integer age;
}
3、读取JSON文件获取字符串
public static String readToString(String fileName) {
String encoding = "UTF-8";
File file = new File(fileName);
Long fileLength = file.length();
byte[] fileContent = new byte[fileLength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(fileContent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(fileContent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return null;
}
}
4、读取JSON文件获取字符串,并转为对象
public static JSONObject readTxtToJson(String txt) {
File file = new File(txt);
String json = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file); // 文件输入流
isr = new InputStreamReader(fis,"utf-8"); // 转为字符流
br = new BufferedReader(isr); // 转为缓冲字符流
String line = "";
//使用readLine方法,一次读一行
while ((line = br.readLine()) != null) {
json += line;
}
System.out.println(json);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return JSONObject.fromObject(json);
}
5、调用方法
public static void main(String[] args) {
String txt = readToString("/Users/admin/Documents/spring.txt");
System.err.println(txt);
JSONObject jsonObject = readTxtToJson("/Users/admin/Desktop/json.txt");
String name = (String) jsonObject.get("name");
Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
System.out.println(name);
System.err.println(person);
}
网友评论