問題:
I'm trying to learn Gson and I'm struggling with field exclusion.我正在嘗試學習 Gson,但我正在努力解決字段排除問題。 Here are my classes這是我的課
public class Student {
private Long id;
private String firstName = "Philip";
private String middleName = "J.";
private String initials = "P.F";
private String lastName = "Fry";
private Country country;
private Country countryOfBirth;
}
public class Country {
private Long id;
private String name;
private Object other;
}
I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName
or country
but I can't seem to manage to exclude properties of certain fields like country.name
.我可以使用 GsonBuilder 併爲字段名稱(如firstName
或country
添加 ExclusionStrategy ,但我似乎無法排除某些字段(如country.name
屬性。
Using the method public boolean shouldSkipField(FieldAttributes fa)
, FieldAttributes doesn't contain enough information to match the field with a filter like country.name
.使用public boolean shouldSkipField(FieldAttributes fa)
,FieldAttributes 不包含足夠的信息來匹配字段與像country.name
這樣的過濾器。
PS: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out. PS:我想避免註釋,因爲我想對此進行改進並使用 RegEx 過濾字段。
Edit : I'm trying to see if it's possible to emulate the behavior of Struts2 JSON plugin編輯:我正在嘗試查看是否可以模擬Struts2 JSON 插件的行爲
using Gson使用 Gson
<interceptor-ref name="json">
<param name="enableSMD">true</param>
<param name="excludeProperties">
login.password,
studentList.*\.sin
</param>
</interceptor-ref>
Edit: I reopened the question with the following addition:編輯:我用以下補充重新打開了這個問題:
I added a second field with the same type to futher clarify this problem.我添加了具有相同類型的第二個字段以進一步闡明這個問題。 Basically I want to exclude country.name
but not countrOfBirth.name
.基本上我想排除country.name
但不是countrOfBirth.name
。 I also don't want to exclude Country as a type.我也不想排除 Country 作爲一種類型。 So the types are the same it's the actual place in the object graph that I want to pinpoint and exclude.所以類型是相同的,它是我想要查明和排除的對象圖中的實際位置。
解決方案:
參考一: https://en.stackoom.com/question/K9Rv參考二: https://stackoom.com/question/K9Rv