我有一种情况,当我试图从父对象制作一个json字符串时,gson也会返回子对象元素。如何消除相同。
这是我的代码。
Class Image {
private int imageID;
private String imageName;
// Getters and setters
}
Class ImageDetails extends Image {
private String imageType;
private byte[] imageData;
//Getters and setters
}
Class Test {
// Setting the image Object, and the imageDetails.
// calling the gson for json string
String jsonString = GsonString.UserFeed(ImageObject)
// This jsonString has all the elements from the ImageDetails Object also which i do not want.
}
Class GsonString {
public static String UserFeed(Object feedData) {
String feeds = null;
Gson gson = new Gson();
feeds = gson.toJson(feedData);
return feeds;
}
}
答案 0 :(得分:1)
您只需使用toJson(Object src,Type typeOfSrc)
指定要序列化的班级一个简单的例子:
class Bob {
private String bobName = "Bob";
}
class Pete extends Bob {
private String peteName = "Bob";
}
public static void main(String[] args) {
Object o = new Pete();
System.out.println(new Gson().toJson(o));
System.out.println(new Gson().toJson(o, Bob.class));
}
<强>输出:强>
{"peteName":"Bob","bobName":"Bob"}
{"bobName":"Bob"}