可能有很多方法可以实现您的愿望。
我将分享两种方法。
FIRST - 使用自定义序列化
第二个 - 使用 JsonAdapter 注解 - 更简单
使用自定义序列化
public static class CarSerializer implements JsonSerializer<Car> {
public JsonElement serialize(final Car car, final Type type, final JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.add("mileage", new JsonPrimitive(Integer.toString(car.getMileage())));
result.add("id", new JsonPrimitive(Integer.toString(car.getId())));
return result;
}
}
要调用它,只需修改您的代码或将以下代码与构造函数一起使用
Car c = new Car(123, 123456789);
com.google.gson.Gson gson = new
GsonBuilder().registerTypeAdapter(Car.class, new CarSerializer())
.create();
System.out.println(gson.toJson(c));
输出应该是
{"mileage":"123","id":"12345678"}
示例 1 的完整代码:
public class SerializationTest {
public static class Car {
public int mileage;
public int id;
public Car(final int mileage, final int id) {
this.mileage = mileage;
this.id = id;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getMileage() {
return mileage;
}
public void setMileage(final String mileage) {
this.mileage = mileage;
}
}
public static class CarSerializer implements JsonSerializer<Car> {
public JsonElement serialize(final Car car, final Type type, final JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.add("mileage", new JsonPrimitive(Integer.toString(car.getMileage())));
result.add("id", new JsonPrimitive(Integer.toString(car.getId())));
return result;
}
}
public static void main(final String[] args) {
Car c = new Car(123, 123456789);
com.google.gson.Gson gson = new
GsonBuilder().registerTypeAdapter(Car.class, new CarSerializer())
.create();
System.out.println(gson.toJson(c));
}
}
使用@JsonAdapter 注解
在 Car 类上使用 JsonAdapter 注解
@JsonAdapter(CarAdapter.class)
public class Car {
public int mileage;
public int id;
}
创建自定义适配器
public class CarAdapter extends TypeAdapter<Car> {
@Override
public void write(JsonWriter writer, Car car) throws IOException {
writer.beginObject();
writer.name("mileage").value(car.getMileage());
writer.name("id").value(car.getId());
writer.endObject();
}
@Override
public Car read(JsonReader in) throws IOException {
// do something you need
return null;
}
}
要序列化,使用这种方法,使用类似这样的东西
Car c = new Car(123, 123456789);
Gson gson = new Gson();
String result = gson.toJson(c);
在这种情况下打印result应该输出
{"mileage":"123","id":"12345678"}