vijju
vijju

Reputation: 35

Gson to json returning all the elements of subclass also

I have a situation where the gson is returning the child object elements also when i tried to make a json string from parent object. how to eliminate the same.

Here is the code i am having.

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;
    }
}

Upvotes: 1

Views: 263

Answers (1)

rpax
rpax

Reputation: 4496

You only have to specify the class you want to serialize, using toJson(Object src,Type typeOfSrc)

A simple example:

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));

}

Output:

{"peteName":"Bob","bobName":"Bob"}
{"bobName":"Bob"}

Upvotes: 1

Related Questions