- 自定义注解接口
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreAnnotation {
}
- 实现ExclusionStrategy接口
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import net.com.server.com.model.IgnoreAnnotation;
public class IgnoreAnnotationExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> clazz) {
return clazz.getAnnotation(IgnoreAnnotation.class) != null;
}
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(IgnoreAnnotation.class) != null;
}
}
- 给属性或类加注解,以GsonBuilder()
.setExclusionStrategies(new IgnoreAnnotationExclusionStrategy())
.create();创建Gson对象
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.com.server.com.model.IgnoreAnnotation;
public class QkTest {
class Test {//{"name":"国标小明"}
private String name;
@IgnoreAnnotation
private int age;
@IgnoreAnnotation
private String sex;
@IgnoreAnnotation
private QkTest.Test1 test2=new QkTest().new Test1("abc", "123", 99999);
public Test(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
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 QkTest.Test1 getTest2() {
return test2;
}
public void setTest2(QkTest.Test1 test2) {
this.test2 = test2;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
class Test1 {//{"name":"国标小明","test2":{"address":"abc","phone":"123","money":99999}}
private String address;
private String phone;
private int money;
public Test1(String address, String phone, int money) {
super();
this.address = address;
this.phone = phone;
this.money = money;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
public static void main(String[] args) {
Gson gson1 = new GsonBuilder()
.setExclusionStrategies(new IgnoreAnnotationExclusionStrategy())
.create();
System.out.println(gson1.toJson(new QkTest().new Test("国标小明", 18, "男")));
//{"name":"国标小明"}
}
}
ok,给需要忽略的属性或类加上自定义注解@IgnoreAnnotation就可以了