public class People {
String name;
int age;
boolean setName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean getSetName() {
return setName;
}
public void setSetName(boolean setName) {
this.setName = setName;
}
@Override
public String toString() {
return "name=" + name + " age=" + age + " setName=" +setName;
}
}
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Convert java object to json.
*/
public class GsonTest {
public static void main(String[] args) {
People p = new People();
p.setAge(20);
p.setName("People");
p.setSetName(true);
Gson gson = new Gson();
System.out.println(gson.toJson(p));
}
}
{"name":"People","age":20,"setName":true}
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Convert java object to json, skip specific fileds.
*/
public class GsonTest {
public static void main(String[] args) {
People p = new People();
p.setAge(20);
p.setName("People");
p.setSetName(true);
ExclusionStrategy excludeStrategy = new SetterExclusionStrategy();
Gson gson1 = new GsonBuilder()
.setExclusionStrategies(excludeStrategy)
.create();
Gson gson2 = new Gson();
String json1 = gson1.toJson(p);
String json2 = gson2.toJson(p);
System.out.println(json1);
System.out.println(json2);
People p1 = gson1.fromJson(json1, People.class);
People p2 = gson2.fromJson(json2, People.class);
System.out.println(p1);
System.out.println(p2);
}
private static class SetterExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
return f.getName().startsWith("set");
}
}
}
{"name":"People","age":20}
{"name":"People","age":20,"setName":true}
name=People age=20 setName=false
name=People age=20 setName=true
public class User {
@Expose private String firstName;
@Expose(serialize = false) private String lastName;
@Expose (serialize = false, deserialize = false) private String emailAddress;
private String password;
}
public class SomeClassWithFields {
@SerializedName("name") private final String someField;
private final String someOtherField;
public SomeClassWithFields(String a, String b) {
this.someField = a;
this.someOtherField = b;
}
}
SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
Gson gson = new Gson();
String jsonRepresentation = gson.toJson(objectToSerialize);
System.out.println(jsonRepresentation);
{"name":"a","someOtherField":"b"}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有