1,从txt文本中读取文件
public static String readTxt2Json(String path) throws IOException {
File file = new File(path);
String jsonStr = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
isr = new InputStreamReader(fis, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine())!= null){
jsonStr += line;
}
//System.out.println(jsonStr);
return jsonStr;
}
2,将txt文件转化为jsonObject
JSONObject jsonObject = JSON.parseObject(str);
System.out.println(jsonObject.get("age"));
System.out.println(jsonObject.get("name"));
其中文本文件为User.txt:
{
"name":"Eric",
"sex":"male",
"age":18
}
3,将文本文件转化为javaBean,文本文件格式为User.txt
User user = JSON.parseObject(str, User.class);
System.out.println(user);
4,将文本文件转化为数组数组,文本文件格式为Users.txt
List<User> users = JSON.parseArray(str, User.class);
System.out.println(users);
[{
"name":"Eric",
"sex":"male",
"age":18
}
{
"name":"Eric",
"sex":"male",
"age":18
}
{
"name":"Eric",
"sex":"male",
"age":18
}]
完整代码如下:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.util.List;
class ReadSomething {
public static void main(String[] args) throws IOException {
System.out.println(readTxt2Json("C:\\Users\\name\\Desktop\\User.txt"));
String str = readTxt2Json("C:\\Users\\name\\Desktop\\UserJson.txt");
JSONObject jsonObject = JSON.parseObject(str);
System.out.println(jsonObject.get("age"));
System.out.println(jsonObject.get("name"));
User user = JSON.parseObject(str, User.class);
System.out.println(user);
/*List<User> users = JSON.parseArray(str, User.class);
System.out.println(users);*/
//http://www.itjson.com/itjson/json2java.html
}
public static String readTxt2Json(String path) throws IOException {
File file = new File(path);
String jsonStr = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
isr = new InputStreamReader(fis, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine())!= null){
jsonStr += line;
}
//System.out.println(jsonStr);
return jsonStr;
}
}
在线json转javaBean网站:http://www.itjson.com/itjson/json2java.html