我们在定义数据结构中,网络通讯中用得最多就是数据结果序列化,经常用到json,有时候我们可能会在数据结构中添加一下辅助功能的字段,但是不想序列化到json中,我们可以使用transient修饰符。如下
public class TestA implements Serializable {
public String a = "aaa";
public int b = 23;
public transient String c = "helloworod";
public transient int d = 22;
@Override
public String toString() {
return "TestA{" +
"a='" + a + '\'' +
", b=" + b +
", c='" + c + '\'' +
", d=" + d +
'}';
}
}
测试执行
TestA test = new TestA();
test.a = "AAA";
test.b = 1;
test.c = "CCC";
test.d = 2;
String json = JsonUtil.toString(test);
LogTool.i(TAG, json);
TestA aTest = JsonUtil.toObject(json, TestA.class);
LogTool.i(TAG, aTest.toString());
输出结果
12-26 14:47:17.557 10312-10312/com.test I/HomeApplication: {"a":"AAA","b":1}
12-26 14:47:21.686 10312-10312/com.test I/HomeApplication: TestA{a='AAA', b=1, c='helloworod', d=22}
这样data就不会被序列化和反序列化。
可以看出,d和c没有被序列化,但是在转化对象的时候,TestA会先初始化,然后在对应复值,导致d和c都是默认初始值,今天的分享就到这里啦
网友评论