博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java字段不序列化注解_gson:如何在没有注释的情况下从序列化中排除特定字段...
阅读量:7069 次
发布时间:2019-06-28

本文共 1886 字,大约阅读时间需要 6 分钟。

所以,你想排除 firstName和country.name..这是你的ExclusionStrategy应该看起来像public class TestExclStrat implements ExclusionStrategy {

public boolean shouldSkipClass(Class> arg0) {

return false;

}

public boolean shouldSkipField(FieldAttributes f) {

return (f.getDeclaringClass() == Student.class && f.getName().equals("firstName"))||

(f.getDeclaringClass() == Country.class && f.getName().equals("name"));

}

}

如果你仔细看,它会回来true为Student.firstName和Country.name这就是你想要排除的。

你需要应用这个ExclusionStrategy像这样,Gson gson = new GsonBuilder()

.setExclusionStrategies(new TestExclStrat())

//.serializeNulls() 

.create();

Student src = new Student();

String json = gson.toJson(src);

System.out.println(json);

返回:{“中间名”:“J”、“首字母”:“P.F”、“最后名称”:“Fry”、“Country”:{“id”:91}

我假设国家对象是用id = 91L在学生课上。

你可能会觉得花哨。例如,您不希望序列化任何在其名称中包含“name”字符串的字段。这样做:public boolean shouldSkipField(FieldAttributes f) {

return f.getName().toLowerCase().contains("name"); }

这将返回:{ "initials": "P.F", "country": { "id": 91 }}

编辑:添加了更多的信息要求。

这,这个ExclusionStrategy会做的事情,但你需要通过“完全限定字段名”。见下文:public class TestExclStrat implements ExclusionStrategy {

private Class> c;

private String fieldName;

public TestExclStrat(String fqfn) throws SecurityException, NoSuchFieldException, ClassNotFoundException

{

this.c = Class.forName(fqfn.substring(0, fqfn.lastIndexOf(".")));

this.fieldName = fqfn.substring(fqfn.lastIndexOf(".")+1);

}

public boolean shouldSkipClass(Class> arg0) {

return false;

}

public boolean shouldSkipField(FieldAttributes f) {

return (f.getDeclaringClass() == c && f.getName().equals(fieldName));

}

}

以下是我们如何泛化使用它。Gson gson = new GsonBuilder()

.setExclusionStrategies(new TestExclStrat("in.naishe.test.Country.name"))

//.serializeNulls()

.create();

Student src = new Student();

String json = gson.toJson(src);

System.out.println(json);

它返回:{ "firstName": "Philip" , "middleName": "J.", "initials": "P.F", "lastName": "Fry", "country": { "id": 91 }}

转载地址:http://svqll.baihongyu.com/

你可能感兴趣的文章
提高Oracle的WHERE语句性能一些原则
查看>>
SQL Server如何在变长列上存储索引
查看>>
Tolerance (定义发票允差)
查看>>
The Promise of Deep Learning
查看>>
C#学习笔记(十一):动态类型
查看>>
Mac在结构quick cocos2d-x编译环境
查看>>
微信、陌陌等著名IM软件设计架构详解
查看>>
4种方法让SpringMVC接收多个对象 <转>
查看>>
问你8个问题,让你马上变清醒
查看>>
iOS - UIImageView - how to handle UIImage image orientation
查看>>
Good Verilog Coding
查看>>
ORACLE 多表关联 UPDATE 语句
查看>>
Android:What is ART?
查看>>
数据结构--画画--最小生成树(Prim算法)
查看>>
(转)Aspone.Cells设置Cell数据格式 Setting Display Formats of Numbers and Dates
查看>>
C# 之 获取服务器IP,客户端IP以及其它
查看>>
java gui 下拉框中项删除按钮
查看>>
专访不足总结
查看>>
raspberry pi2 智能小车源码及测试视频
查看>>
Java Properties工具类详解
查看>>