Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42758

How to read the old json string, if you decide to rename fields in class (Using gson)

Previously, we have the following class

public class Checklist {
    private final long id;
    private String text;
    private boolean checked;

    public Checklist(long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public long getId() {
        return id;
    }
}

The following json operation (String to object) works pretty well.

String string = "[{\"checked\":false,\"id\":0,\"text\":\"Boodschappen\"},{\"checked\":false,\"id\":1,\"text\":\"Melk\"}]";

GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
List<Checklist> checklists = gson.fromJson(string, new TypeToken<List<Checklist>>() {}.getType());

for (Checklist checklist : checklists) {
    System.out.println("--> " + checklist.getText());
}

Now, we "upgrade" the class to the following, in order to preserve disk space.

public class Checklist {

    @SerializedName("i")
    private final long id;
    @SerializedName("t")
    private String text;
    @SerializedName("c")
    private boolean checked;

    public Checklist(long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public long getId() {
        return id;
    }
}

It will work with new json String

String string = "[{\"c\":false,\"i\":0,\"t\":\"Boodschappen\"},{\"c\":false,\"i\":1,\"t\":\"Melk\"}]";

GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
List<Checklist> checklists = gson.fromJson(string, new TypeToken<List<Checklist>>() {}.getType());

for (Checklist checklist : checklists) {
    System.out.println("--> " + checklist.getText());
}

But, we still would like to able, to convert the old json string back to new Object.

String oldString = "[{\"checked\":false,\"id\":0,\"text\":\"Boodschappen\"},{\"checked\":false,\"id\":1,\"text\":\"Melk\"}]";

May I know how I can achieve so?

Upvotes: 1

Views: 73

Answers (1)

Dinesh K
Dinesh K

Reputation: 299

You can pass alternate as an argument to SerializedName

@SerializedName(value = "fullName", alternate = "username")

Please refer to this Javadoc

Upvotes: 2

Related Questions