Created
September 18, 2020 10:25
-
-
Save 911992/03120393d31b24ed3c069c2698cde07d to your computer and use it in GitHub Desktop.
including transient field in gson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Lic: BSD 3.0 | |
*/ | |
/* | |
sample_code_java0 | |
File: Gson_Transient.java | |
Created on: Sep 18, 2020 1:51:02 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.TypeAdapter; | |
import com.google.gson.annotations.JsonAdapter; | |
import com.google.gson.annotations.SerializedName; | |
import com.google.gson.stream.JsonReader; | |
import com.google.gson.stream.JsonWriter; | |
import java.io.IOException; | |
/** | |
* | |
* @author https://github.com/911992 | |
*/ | |
public class Gson_Transient { | |
public static void main(String[] args) { | |
GsonBuilder _gb=new GsonBuilder(); | |
Gson _g = _gb.create(); | |
String _js = _g.toJson(new Entity()); | |
System.out.println(_js); | |
Entity _k = _g.fromJson(_js, Entity.class); | |
System.out.printf("Name: %s , password:%s\n",_k.getName(),_k.getPassword()); | |
} | |
} | |
class Entity_Adapter extends TypeAdapter<Entity>{ | |
@Override | |
public void write(JsonWriter out, Entity value) throws IOException { | |
out.beginObject(); | |
out.name("name"); | |
out.value(value.getName()); | |
out.name("password"); | |
out.value(value.getPassword()); | |
out.endObject(); | |
} | |
@Override | |
public Entity read(JsonReader in) throws IOException { | |
Entity k=new Entity(); | |
in.beginObject(); | |
in.nextName(); | |
k.setName(in.nextString()); | |
in.nextName(); | |
k.setPassword(in.nextString()); | |
in.endObject(); | |
return k; | |
} | |
} | |
@JsonAdapter(Entity_Adapter.class) | |
class Entity{ | |
private String name = "user911992"; | |
private transient String password="123456-best-password"; | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public String getPassword() { | |
return password; | |
} | |
public void setPassword(String password) { | |
this.password = password; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment