gson和bson4jackson 的簡單記錄
阿新 • • 發佈:2019-02-07
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import de.undercouch.bson4jackson.BsonFactory; public class jack { public static void main(String ss[]) throws Exception { testuser t=new testuser(); t.setId(1); t.setUsername("admin"); t.setPassword("admin88888"); Gson gson = new Gson(); String str = gson.toJson(t); FileOutputStream in = new FileOutputStream("c:/jack1.bin"); in.write(str.getBytes()); in.flush(); in.close(); FileOutputStream baos = new FileOutputStream("c:/jack.bin"); ObjectMapper mapper = new ObjectMapper(new BsonFactory()); mapper.writeValue(baos, t); baos.flush(); baos.close(); FileInputStream bais = new FileInputStream("c:/jack.bin"); testuser t2 = mapper.readValue(bais, testuser.class); t2.info(); bais.close(); } }
//pojo testuser
public class testuser { private int id; private String username; private String password ; public testuser() { // TODO Auto-generated constructor stub } public void setId(int id) { this.id = id; } public void setPassword(String password) { this.password = password; } public void setUsername(String username) { this.username = username; } public int getId() { return id; } public String getPassword() { return password; } public String getUsername() { return username; } public void info() { System.out.println("id:"+id+":"+username+":"+password); } }