JAVA Oject转List

前言: 从网上找Objec转List方法,搜了挺多但是未找到合适的,但是仔细想想这个应该也不难
只要借助Gson就可以将object转list

代码:

package com.mvc.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mvc.model.User;

public class SerializableTest {
	
	
	public static void main(String[] args) {
		SerializableTest test = new SerializableTest();
		
		test.writeUserToDisk();
		
		test.readDiskToList();
		
		
	}
	
	public void readDiskToList(){
		
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("E:\\download.txt")));
			
			Object listuser =  in.readObject();
			
			 Gson gson = new Gson();
			 
			  List users = gson.fromJson(listuser.toString(), new TypeToken>() {
		        }.getType());//对于不是类的情况,用这个参数给出
		        for (User person : users) {
		            System.out.println(person);
		        }    
			System.out.println(users.toString());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public void writeUserToDisk(){
		

		List userlist = new ArrayList();
		
		User user = new User(1,"ooo","ppp",12,45);
		
		User user1 = new User(2,"oodddo","ppaaap",12,45);
		
		userlist.add(user);
		userlist.add(user1);
		
		Gson gson = new Gson();
		
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("E:\\download.txt")));
			
			out.writeObject(gson.toJson(userlist));
			
			out.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}

科学上网链接:

https://javastudy.mynatapp.cc/kxsw/f/wechat/interLine/index

相关的教程可以参考我的其他博客

你可能感兴趣的:(JAVA Oject转List)