对象数组实例化,再转换成对象数组


import java.io.BufferedReader;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.alibaba.fastjson.JSON;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class MyTest

{


public static void main(String[] args)
{
List<Student> students = new ArrayList<>();
List<Student> finallyStudents = new ArrayList<>();
Student student01 = new Student("Andy", 22, 180.1);
Student student02 = new Student("Brown", 31, 179.2);
Student student03 = new Student("Cili", 27, 170.1);
Student student04 = new Student("Dndy", 26, 180.1);
Student student05 = new Student("Erown", 31, 179.2);
Student student06 = new Student("Fili", 27, 170.1);


students.add(student01);
students.add(student02);
students.add(student03);
students.add(student04);
students.add(student05);
students.add(student06);
for (Student student : students)
{
if (student.getAge() > 25)
{
finallyStudents.add(student);
}
}
for (Student student : students)
{
System.out.println(student);
}
String json = JSON.toJSONString(finallyStudents);
instantiateToFile(json, "C:\\Users\\coder\\Desktop\\error.txt");
String object = getFile("C:\\Users\\coder\\Desktop\\error.txt");
System.out.println(object);
List<Student> s = new ArrayList<>();
JSONArray array = JSONArray.fromObject(object);
for (int i = 0; i < array.length(); i++)
{
JSONObject jsonObject = array.getJSONObject(i);
// 转成实体对象
Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
s.add(student);
}
Collections.sort(s);
for (Student student : s)
{
System.out.println(student);
}
}


private static <T> void instantiateToFile(String json, String filePath)
{
try
{
PrintWriter p = new PrintWriter(new FileOutputStream(filePath, true));
p.println(json);
p.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}


private static String getFile(String filePath)
{
String resultString = "";
Reader reader;
try
{
reader = new FileReader(filePath);
// 构建高效流对象
BufferedReader buffReader = new BufferedReader(reader);


// 2、读取一行字符串
String line = buffReader.readLine();
StringBuffer buffer = new StringBuffer();
while (line != null)
{
buffer.append(line + "\r\n");
line = buffReader.readLine();
}
resultString = buffer.toString();
// 3、关闭流
buffReader.close();
reader.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultString;
}
}
阅读更多
换一批

没有更多推荐了,返回首页