In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods
关于属性值和 get/set 方法是这样的
access to properties using getter and setter methods
A Java serialization/deserialization library to convert Java Objects into JSON and back
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
@Test
public void fastjson() {
People people = new People();
people.setName("八戒");
people.setWeight(100.00);
people.setHeight(1.70);
people.setBmi(30);
log.info(JSON.toJSONString(people));
}
@Test
public void gson() {
People people = new People();
people.setName("八戒");
people.setWeight(100.00);
people.setHeight(1.70);
people.setBmi(30);
log.info(new Gson().toJson((people)));
}
public class People {
/** 姓名 **/
private String name;
/** 身高 m **/
private double height;
/** 体重 kg **/
private double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getBmi() {
return weight / (height * height);
}
}
@Test
public void fastjson() {
People people = new People();
people.setName("八戒");
people.setWeight(100.00);
people.setHeight(1.70);
// people.setBmi(30);
log.info(JSON.toJSONString(people));
}
@Test
public void gson() {
People people = new People();
people.setName("八戒");
people.setWeight(100.00);
people.setHeight(1.70);
// people.setBmi(30);
log.info(new Gson().toJson((people)));
}
{"name":"八戒","height":1.7,"weight":100.0}
public class Car {
private String brand;
private long speed;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public long getSpeed() {
if (speed < 100) {
speed = 100;
} else {
speed = 200;
}
return speed;
}
}
@Test
public void test() {
Car car = new Car();
car.setBrand("bmw");
String json = JSON.toJSONString(car);
log.info(json);
Car car1 = JSON.parseObject(json, Car.class);
Assert.assertNotEquals(car.getSpeed(), car1.getSpeed());
}