Reputation: 42758
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