Skip to content

Commit aacfa94

Browse files
committed
🎨 统一优化gson adapter类,抽取常量,优化重复代码
1 parent 3e4ee57 commit aacfa94

File tree

5 files changed

+326
-320
lines changed

5 files changed

+326
-320
lines changed

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java

Lines changed: 82 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,3 @@
1-
/*
2-
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
3-
*
4-
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
5-
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
6-
* arose from modification of the original source, or other redistribution of this source
7-
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
8-
*/
91
package me.chanjar.weixin.common.util.json;
102

113
import com.google.gson.*;
@@ -14,118 +6,134 @@
146
import me.chanjar.weixin.common.bean.menu.WxMenuRule;
157

168
import java.lang.reflect.Type;
9+
import java.util.Optional;
1710

1811

1912
/**
2013
* @author Daniel Qian
2114
*/
2215
public class WxMenuGsonAdapter implements JsonSerializer<WxMenu>, JsonDeserializer<WxMenu> {
2316

17+
// JSON字段常量定义
18+
private static final String FIELD_BUTTON = "button";
19+
private static final String FIELD_MATCH_RULE = "matchrule";
20+
private static final String FIELD_SUB_BUTTON = "sub_button";
21+
private static final String FIELD_MENU = "menu";
22+
23+
// 菜单按钮字段常量
24+
private static final String FIELD_TYPE = "type";
25+
private static final String FIELD_NAME = "name";
26+
private static final String FIELD_KEY = "key";
27+
private static final String FIELD_URL = "url";
28+
private static final String FIELD_MEDIA_ID = "media_id";
29+
private static final String FIELD_ARTICLE_ID = "article_id";
30+
private static final String FIELD_APP_ID = "appid";
31+
private static final String FIELD_PAGE_PATH = "pagepath";
32+
33+
// 菜单规则字段常量
34+
private static final String FIELD_TAG_ID = "tag_id";
35+
private static final String FIELD_SEX = "sex";
36+
private static final String FIELD_COUNTRY = "country";
37+
private static final String FIELD_PROVINCE = "province";
38+
private static final String FIELD_CITY = "city";
39+
private static final String FIELD_CLIENT_PLATFORM_TYPE = "client_platform_type";
40+
private static final String FIELD_LANGUAGE = "language";
41+
2442
@Override
2543
public JsonElement serialize(WxMenu menu, Type typeOfSrc, JsonSerializationContext context) {
2644
JsonObject json = new JsonObject();
27-
2845
JsonArray buttonArray = new JsonArray();
29-
for (WxMenuButton button : menu.getButtons()) {
30-
JsonObject buttonJson = convertToJson(button);
31-
buttonArray.add(buttonJson);
32-
}
33-
json.add("button", buttonArray);
34-
46+
Optional.ofNullable(menu.getButtons())
47+
.ifPresent(buttons -> buttons.stream()
48+
.map(this::convertToJson)
49+
.forEach(buttonArray::add));
50+
json.add(FIELD_BUTTON, buttonArray);
3551
if (menu.getMatchRule() != null) {
36-
json.add("matchrule", convertToJson(menu.getMatchRule()));
52+
json.add(FIELD_MATCH_RULE, convertToJson(menu.getMatchRule()));
3753
}
38-
3954
return json;
4055
}
4156

4257
protected JsonObject convertToJson(WxMenuButton button) {
4358
JsonObject buttonJson = new JsonObject();
44-
buttonJson.addProperty("type", button.getType());
45-
buttonJson.addProperty("name", button.getName());
46-
buttonJson.addProperty("key", button.getKey());
47-
buttonJson.addProperty("url", button.getUrl());
48-
buttonJson.addProperty("media_id", button.getMediaId());
49-
buttonJson.addProperty("article_id", button.getArticleId());
50-
buttonJson.addProperty("appid", button.getAppId());
51-
buttonJson.addProperty("pagepath", button.getPagePath());
59+
addPropertyIfNotNull(buttonJson, FIELD_TYPE, button.getType());
60+
addPropertyIfNotNull(buttonJson, FIELD_NAME, button.getName());
61+
addPropertyIfNotNull(buttonJson, FIELD_KEY, button.getKey());
62+
addPropertyIfNotNull(buttonJson, FIELD_URL, button.getUrl());
63+
addPropertyIfNotNull(buttonJson, FIELD_MEDIA_ID, button.getMediaId());
64+
addPropertyIfNotNull(buttonJson, FIELD_ARTICLE_ID, button.getArticleId());
65+
addPropertyIfNotNull(buttonJson, FIELD_APP_ID, button.getAppId());
66+
addPropertyIfNotNull(buttonJson, FIELD_PAGE_PATH, button.getPagePath());
5267
if (button.getSubButtons() != null && !button.getSubButtons().isEmpty()) {
5368
JsonArray buttonArray = new JsonArray();
54-
for (WxMenuButton sub_button : button.getSubButtons()) {
55-
buttonArray.add(convertToJson(sub_button));
56-
}
57-
buttonJson.add("sub_button", buttonArray);
69+
button.getSubButtons().stream()
70+
.map(this::convertToJson)
71+
.forEach(buttonArray::add);
72+
buttonJson.add(FIELD_SUB_BUTTON, buttonArray);
5873
}
5974
return buttonJson;
6075
}
6176

6277
protected JsonObject convertToJson(WxMenuRule menuRule) {
6378
JsonObject matchRule = new JsonObject();
64-
matchRule.addProperty("tag_id", menuRule.getTagId());
65-
matchRule.addProperty("sex", menuRule.getSex());
66-
matchRule.addProperty("country", menuRule.getCountry());
67-
matchRule.addProperty("province", menuRule.getProvince());
68-
matchRule.addProperty("city", menuRule.getCity());
69-
matchRule.addProperty("client_platform_type", menuRule.getClientPlatformType());
70-
matchRule.addProperty("language", menuRule.getLanguage());
79+
addPropertyIfNotNull(matchRule, FIELD_TAG_ID, menuRule.getTagId());
80+
addPropertyIfNotNull(matchRule, FIELD_SEX, menuRule.getSex());
81+
addPropertyIfNotNull(matchRule, FIELD_COUNTRY, menuRule.getCountry());
82+
addPropertyIfNotNull(matchRule, FIELD_PROVINCE, menuRule.getProvince());
83+
addPropertyIfNotNull(matchRule, FIELD_CITY, menuRule.getCity());
84+
addPropertyIfNotNull(matchRule, FIELD_CLIENT_PLATFORM_TYPE, menuRule.getClientPlatformType());
85+
addPropertyIfNotNull(matchRule, FIELD_LANGUAGE, menuRule.getLanguage());
7186
return matchRule;
7287
}
7388

74-
@Deprecated
75-
private WxMenuRule convertToRule(JsonObject json) {
76-
WxMenuRule menuRule = new WxMenuRule();
77-
//变态的微信接口,这里居然反人类的使用和序列化时不一样的名字
78-
//menuRule.setTagId(GsonHelper.getString(json,"tag_id"));
79-
menuRule.setTagId(GsonHelper.getString(json, "group_id"));
80-
menuRule.setSex(GsonHelper.getString(json, "sex"));
81-
menuRule.setCountry(GsonHelper.getString(json, "country"));
82-
menuRule.setProvince(GsonHelper.getString(json, "province"));
83-
menuRule.setCity(GsonHelper.getString(json, "city"));
84-
menuRule.setClientPlatformType(GsonHelper.getString(json, "client_platform_type"));
85-
menuRule.setLanguage(GsonHelper.getString(json, "language"));
86-
return menuRule;
89+
private void addPropertyIfNotNull(JsonObject obj, String key, String value) {
90+
if (value != null) {
91+
obj.addProperty(key, value);
92+
}
8793
}
8894

8995
@Override
9096
public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
91-
/*
92-
* 操蛋的微信
93-
* 创建菜单时是 { button : ... }
94-
* 查询菜单时是 { menu : { button : ... } }
95-
* 现在企业号升级为企业微信后,没有此问题,因此需要单独处理
96-
*/
97-
JsonArray buttonsJson = json.getAsJsonObject().get("menu").getAsJsonObject().get("button").getAsJsonArray();
98-
return this.buildMenuFromJson(buttonsJson);
97+
JsonObject root = json.getAsJsonObject();
98+
JsonArray buttonsJson = null;
99+
if (root.has(FIELD_MENU)) {
100+
JsonObject menuObj = root.getAsJsonObject(FIELD_MENU);
101+
buttonsJson = menuObj.getAsJsonArray(FIELD_BUTTON);
102+
} else if (root.has(FIELD_BUTTON)) {
103+
buttonsJson = root.getAsJsonArray(FIELD_BUTTON);
104+
}
105+
if (buttonsJson == null) {
106+
throw new JsonParseException("No button array found in menu JSON");
107+
}
108+
return buildMenuFromJson(buttonsJson);
99109
}
100110

101111
protected WxMenu buildMenuFromJson(JsonArray buttonsJson) {
102112
WxMenu menu = new WxMenu();
103-
for (int i = 0; i < buttonsJson.size(); i++) {
104-
JsonObject buttonJson = buttonsJson.get(i).getAsJsonObject();
113+
for (JsonElement btnElem : buttonsJson) {
114+
JsonObject buttonJson = btnElem.getAsJsonObject();
105115
WxMenuButton button = convertFromJson(buttonJson);
106116
menu.getButtons().add(button);
107-
if (buttonJson.get("sub_button") == null || buttonJson.get("sub_button").isJsonNull()) {
108-
continue;
109-
}
110-
JsonArray sub_buttonsJson = buttonJson.get("sub_button").getAsJsonArray();
111-
for (int j = 0; j < sub_buttonsJson.size(); j++) {
112-
JsonObject sub_buttonJson = sub_buttonsJson.get(j).getAsJsonObject();
113-
button.getSubButtons().add(convertFromJson(sub_buttonJson));
117+
if (buttonJson.has(FIELD_SUB_BUTTON) && buttonJson.get(FIELD_SUB_BUTTON).isJsonArray()) {
118+
JsonArray sub_buttonsJson = buttonJson.getAsJsonArray(FIELD_SUB_BUTTON);
119+
for (JsonElement subBtnElem : sub_buttonsJson) {
120+
button.getSubButtons().add(convertFromJson(subBtnElem.getAsJsonObject()));
121+
}
114122
}
115123
}
116124
return menu;
117125
}
118126

119127
protected WxMenuButton convertFromJson(JsonObject json) {
120128
WxMenuButton button = new WxMenuButton();
121-
button.setName(GsonHelper.getString(json, "name"));
122-
button.setKey(GsonHelper.getString(json, "key"));
123-
button.setUrl(GsonHelper.getString(json, "url"));
124-
button.setType(GsonHelper.getString(json, "type"));
125-
button.setMediaId(GsonHelper.getString(json, "media_id"));
126-
button.setArticleId(GsonHelper.getString(json, "article_id"));
127-
button.setAppId(GsonHelper.getString(json, "appid"));
128-
button.setPagePath(GsonHelper.getString(json, "pagepath"));
129+
button.setName(GsonHelper.getString(json, FIELD_NAME));
130+
button.setKey(GsonHelper.getString(json, FIELD_KEY));
131+
button.setUrl(GsonHelper.getString(json, FIELD_URL));
132+
button.setType(GsonHelper.getString(json, FIELD_TYPE));
133+
button.setMediaId(GsonHelper.getString(json, FIELD_MEDIA_ID));
134+
button.setArticleId(GsonHelper.getString(json, FIELD_ARTICLE_ID));
135+
button.setAppId(GsonHelper.getString(json, FIELD_APP_ID));
136+
button.setPagePath(GsonHelper.getString(json, FIELD_PAGE_PATH));
129137
return button;
130138
}
131139

weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java

Lines changed: 19 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,3 @@
1-
/*
2-
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
3-
*
4-
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
5-
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
6-
* arose from modification of the original source, or other redistribution of this source
7-
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
8-
*/
91
package me.chanjar.weixin.cp.util.json;
102

113
import com.google.gson.*;
@@ -23,46 +15,44 @@
2315
*/
2416
public class WxCpChatGsonAdapter implements JsonSerializer<WxCpChat>, JsonDeserializer<WxCpChat> {
2517

18+
public static final String FIELD_CHAT_ID = "chatid";
19+
public static final String FIELD_NAME = "name";
20+
public static final String FIELD_OWNER = "owner";
21+
public static final String FIELD_USER_LIST = "userlist";
22+
2623
@Override
2724
public JsonElement serialize(WxCpChat chat, Type typeOfSrc, JsonSerializationContext context) {
2825
JsonObject json = new JsonObject();
29-
if (chat.getId() != null) {
30-
json.addProperty("chatid", chat.getId());
31-
}
32-
if (chat.getName() != null) {
33-
json.addProperty("name", chat.getName());
34-
}
35-
if (chat.getOwner() != null) {
36-
json.addProperty("owner", chat.getOwner());
37-
}
38-
if (chat.getUsers() != null) {
26+
addPropertyIfNotNull(json, FIELD_CHAT_ID, chat.getId());
27+
addPropertyIfNotNull(json, FIELD_NAME, chat.getName());
28+
addPropertyIfNotNull(json, FIELD_OWNER, chat.getOwner());
29+
if (chat.getUsers() != null && !chat.getUsers().isEmpty()) {
3930
JsonArray users = new JsonArray();
40-
for (String user : chat.getUsers()) {
41-
users.add(user);
42-
}
43-
json.add("userlist", users);
31+
chat.getUsers().forEach(users::add);
32+
json.add(FIELD_USER_LIST, users);
4433
}
4534
return json;
4635
}
4736

37+
private void addPropertyIfNotNull(JsonObject json, String key, String value) {
38+
if (value != null) {
39+
json.addProperty(key, value);
40+
}
41+
}
42+
4843
@Override
4944
public WxCpChat deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
5045
JsonObject chatJson = json.getAsJsonObject();
51-
5246
WxCpChat chat = new WxCpChat();
5347
chat.setId(GsonHelper.getAsString(chatJson.get("chatid")));
5448
chat.setName(GsonHelper.getAsString(chatJson.get("name")));
5549
chat.setOwner(GsonHelper.getAsString(chatJson.get("owner")));
56-
5750
JsonArray usersJson = chatJson.getAsJsonArray("userlist");
58-
if (usersJson != null) {
51+
if (usersJson != null && !usersJson.isEmpty()) {
5952
List<String> users = new ArrayList<>(usersJson.size());
53+
usersJson.forEach(e -> users.add(e.getAsString()));
6054
chat.setUsers(users);
61-
for (JsonElement userJson : usersJson) {
62-
users.add(userJson.getAsString());
63-
}
6455
}
65-
6656
return chat;
6757
}
6858

weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java

Lines changed: 28 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,12 @@
1-
/*
2-
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
3-
*
4-
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
5-
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
6-
* arose from modification of the original source, or other redistribution of this source
7-
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
8-
*/
91
package me.chanjar.weixin.cp.util.json;
102

113
import com.google.gson.*;
124
import me.chanjar.weixin.common.util.json.GsonHelper;
135
import me.chanjar.weixin.cp.bean.WxCpDepart;
146

157
import java.lang.reflect.Type;
8+
import java.util.Arrays;
9+
import java.util.Objects;
1610

1711
/**
1812
* WxCpDepart的gson适配器.
@@ -30,60 +24,47 @@ public class WxCpDepartGsonAdapter implements JsonSerializer<WxCpDepart>, JsonDe
3024
@Override
3125
public JsonElement serialize(WxCpDepart group, Type typeOfSrc, JsonSerializationContext context) {
3226
JsonObject json = new JsonObject();
33-
if (group.getId() != null) {
34-
json.addProperty(ID, group.getId());
35-
}
36-
if (group.getName() != null) {
37-
json.addProperty(NAME, group.getName());
38-
}
39-
if (group.getEnName() != null) {
40-
json.addProperty(EN_NAME, group.getEnName());
41-
}
42-
if (group.getDepartmentLeader() != null) {
27+
addPropertyIfNotNull(json, ID, group.getId());
28+
addPropertyIfNotNull(json, NAME, group.getName());
29+
addPropertyIfNotNull(json, EN_NAME, group.getEnName());
30+
if (group.getDepartmentLeader() != null && group.getDepartmentLeader().length > 0) {
4331
JsonArray jsonArray = new JsonArray();
44-
for (String department : group.getDepartmentLeader()) {
45-
jsonArray.add(new JsonPrimitive(department));
46-
}
32+
Arrays.stream(group.getDepartmentLeader()).filter(Objects::nonNull).forEach(jsonArray::add);
4733
json.add(DEPARTMENT_LEADER, jsonArray);
4834
}
49-
if (group.getParentId() != null) {
50-
json.addProperty(PARENT_ID, group.getParentId());
51-
}
52-
if (group.getOrder() != null) {
53-
json.addProperty(ORDER, String.valueOf(group.getOrder()));
54-
}
35+
addPropertyIfNotNull(json, PARENT_ID, group.getParentId());
36+
addPropertyIfNotNull(json, ORDER, group.getOrder());
5537
return json;
5638
}
5739

40+
private void addPropertyIfNotNull(JsonObject json, String key, Object value) {
41+
if (value != null) {
42+
if (value instanceof Number) {
43+
json.addProperty(key, (Number) value);
44+
} else {
45+
json.addProperty(key, value.toString());
46+
}
47+
}
48+
}
49+
5850
@Override
5951
public WxCpDepart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
6052
throws JsonParseException {
6153
WxCpDepart depart = new WxCpDepart();
6254
JsonObject departJson = json.getAsJsonObject();
63-
if (departJson.get(ID) != null && !departJson.get(ID).isJsonNull()) {
64-
depart.setId(GsonHelper.getAsLong(departJson.get(ID)));
65-
}
66-
if (departJson.get(NAME) != null && !departJson.get(NAME).isJsonNull()) {
67-
depart.setName(GsonHelper.getAsString(departJson.get(NAME)));
68-
}
69-
if (departJson.get(EN_NAME) != null && !departJson.get(EN_NAME).isJsonNull()) {
70-
depart.setEnName(GsonHelper.getAsString(departJson.get(EN_NAME)));
71-
}
72-
if (departJson.getAsJsonArray(DEPARTMENT_LEADER) != null && !departJson.get(DEPARTMENT_LEADER).isJsonNull()) {
73-
JsonArray jsonArray = departJson.getAsJsonArray(DEPARTMENT_LEADER);
55+
depart.setId(GsonHelper.getAsLong(departJson.get(ID)));
56+
depart.setName(GsonHelper.getAsString(departJson.get(NAME)));
57+
depart.setEnName(GsonHelper.getAsString(departJson.get(EN_NAME)));
58+
JsonArray jsonArray = departJson.getAsJsonArray(DEPARTMENT_LEADER);
59+
if (jsonArray != null && !jsonArray.isJsonNull()) {
7460
String[] departments = new String[jsonArray.size()];
75-
int i = 0;
76-
for (JsonElement jsonElement : jsonArray) {
77-
departments[i++] = jsonElement.getAsString();
61+
for (int i = 0; i < jsonArray.size(); i++) {
62+
departments[i] = jsonArray.get(i).getAsString();
7863
}
7964
depart.setDepartmentLeader(departments);
8065
}
81-
if (departJson.get(ORDER) != null && !departJson.get(ORDER).isJsonNull()) {
82-
depart.setOrder(GsonHelper.getAsLong(departJson.get(ORDER)));
83-
}
84-
if (departJson.get(PARENT_ID) != null && !departJson.get(PARENT_ID).isJsonNull()) {
85-
depart.setParentId(GsonHelper.getAsLong(departJson.get(PARENT_ID)));
86-
}
66+
depart.setOrder(GsonHelper.getAsLong(departJson.get(ORDER)));
67+
depart.setParentId(GsonHelper.getAsLong(departJson.get(PARENT_ID)));
8768
return depart;
8869
}
8970

0 commit comments

Comments
 (0)