Skip to content

Instantly share code, notes, and snippets.

@911992
Created September 18, 2020 10:45
Show Gist options
  • Save 911992/8a4bb7f84beb974730eaaecb7885d967 to your computer and use it in GitHub Desktop.
Save 911992/8a4bb7f84beb974730eaaecb7885d967 to your computer and use it in GitHub Desktop.
including transient field in gson
/*
* Lic: BSD 3
*/
/*
sample_code_java0
File: Gson_Transient1.java
Created on: Sep 18, 2020 2:33:06 AM
@author https://github.com/911992
History:
initial version: 0.1(20200918)
*/
package gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
/**
*
* @author https://github.com/911992
*/
public class Gson_Transient1 {
public static void main(String[] args) {
GsonBuilder _gb = new GsonBuilder();
Gson _g = _gb.create();
Type _t = new Type();
_t.setName("911992");
_t.setPasswd("qwerty");
String _js = _g.toJson(_t);
System.out.printf("Json: %s\n",_js);
Type _t1 = _g.fromJson(_js, Type.class);
System.out.printf("name:%s , pass:%s\n",_t1.getName(),_t1.getPasswd());
// //manual passwd_non_tran copy to passwd
// _t1.finish_object_deserializing();
// System.out.printf("After val-copy name:%s , pass:%s\n",_t1.getName(),_t1.getPasswd());
}
}
class Type{
private String name;
private transient String passwd;
@SerializedName("passwd")
private String passwd_non_tran;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
/*if the pass is null, then copy the result of passwd_non_tran*/
if(this.passwd==null){
this.passwd = this.passwd_non_tran;
}
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
this.passwd_non_tran = passwd;
}
// public String getPasswd_non_tran() {
// return passwd_non_tran;
// }
//
// public void setPasswd_non_tran(String passwd_non_tran) {
// this.passwd_non_tran = passwd_non_tran;
// }
// public void finish_object_deserializing(){
// this.passwd = this.passwd_non_tran;
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment