我想编写一个扩展另一个类的新类,并在新类中定义一个与父类同名的变量。我可以在Java中做到这一点,因为两者都是私有的,但是当我尝试使用gson序列化对象时,由于存在两个具有相同名称的属性(即使从父类继承的属性为null,因此不应该这样做),我也会收到错误消息包含在json中。)
例如考虑以下类:
public class Car {
private String color;
private Seat seat;
}
public class Seat {
private boolean isAdjustable;
}
和这些类:
public class FancyCar extends Car {
private FancySeat seat;
private boolean hasSpoiler;
}
public class Fancyseat extends Seat {
private boolean hasSeatWarmers;
}
使用这些类,我可以创建一个新的FancyCar,其座椅为isAdjustable和hasSeatWarmers。但是,如果我要使用gson进行序列化,则它将尝试解析两个名为seat的变量,即使从Car继承的变量为null。
有没有更好的方法来设计这些类?还是一种让gson完全忽略空字段的方法?
答案 0 :(得分:0)
您可以使用@SerializedName(value =“ fancySeat”)。此外,从Gson版本开始。2.4反序列化时,有一个选项可以为serializedName替换或具有多个名称。不需要CustomTypeadapter。
Gson Field Naming
Example for Multiple deserialization names
package com.test.practice;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class JsonSerializationExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Seat seatCar = new Seat();
seatCar.setAdjustable(true);
Fancyseat fancySeat = new Fancyseat();
fancySeat.setHasSeatWarmers(true);
fancySeat.setAdjustable(false);
Car car = new Car();
car.setColor("black");
car.setSeat(seatCar);
FancyCar fancyCar = new FancyCar();
fancyCar.setColor("white");
fancyCar.setSeat(fancySeat);
Gson gson = new Gson();
String jsonString = gson.toJson(fancyCar);
System.out.println("json :: "+jsonString);
}
}
class Car {
private String color;
private Seat seat;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Seat getSeat() {
return seat;
}
public void setSeat(Seat seat) {
this.seat = seat;
}
}
class Seat {
private boolean isAdjustable;
public boolean isAdjustable() {
return isAdjustable;
}
public void setAdjustable(boolean isAdjustable) {
this.isAdjustable = isAdjustable;
}
}
class FancyCar extends Car {
@SerializedName(value = "fancySeat")
private Fancyseat seat;
private boolean hasSpoiler;
public Fancyseat getSeat() {
return seat;
}
public void setSeat(Fancyseat seat) {
this.seat = seat;
}
public boolean isHasSpoiler() {
return hasSpoiler;
}
public void setHasSpoiler(boolean hasSpoiler) {
this.hasSpoiler = hasSpoiler;
}
}
class Fancyseat extends Seat {
private boolean hasSeatWarmers;
public boolean isHasSeatWarmers() {
return hasSeatWarmers;
}
public void setHasSeatWarmers(boolean hasSeatWarmers) {
this.hasSeatWarmers = hasSeatWarmers;
}
}