From aacfa947beb3a9b949522ee260525c37f3d7b3fb Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 16 Jul 2025 13:50:47 +0800 Subject: [PATCH] =?UTF-8?q?:art:=20=E7=BB=9F=E4=B8=80=E4=BC=98=E5=8C=96gso?= =?UTF-8?q?n=20adapter=E7=B1=BB=EF=BC=8C=E6=8A=BD=E5=8F=96=E5=B8=B8?= =?UTF-8?q?=E9=87=8F=EF=BC=8C=E4=BC=98=E5=8C=96=E9=87=8D=E5=A4=8D=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/util/json/WxMenuGsonAdapter.java | 156 ++++---- .../cp/util/json/WxCpChatGsonAdapter.java | 48 +-- .../cp/util/json/WxCpDepartGsonAdapter.java | 75 ++-- .../cp/util/json/WxCpTagGsonAdapter.java | 23 +- .../cp/util/json/WxCpUserGsonAdapter.java | 342 ++++++++++-------- 5 files changed, 325 insertions(+), 319 deletions(-) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java index 6e12aa502..5e7f9b41d 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java @@ -1,11 +1,3 @@ -/* - * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. - * - * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended - * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction - * arose from modification of the original source, or other redistribution of this source - * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. - */ package me.chanjar.weixin.common.util.json; import com.google.gson.*; @@ -14,6 +6,7 @@ import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.bean.menu.WxMenuRule; import java.lang.reflect.Type; +import java.util.Optional; /** @@ -21,96 +14,111 @@ import java.lang.reflect.Type; */ public class WxMenuGsonAdapter implements JsonSerializer, JsonDeserializer { + // JSON字段常量定义 + private static final String FIELD_BUTTON = "button"; + private static final String FIELD_MATCH_RULE = "matchrule"; + private static final String FIELD_SUB_BUTTON = "sub_button"; + private static final String FIELD_MENU = "menu"; + + // 菜单按钮字段常量 + private static final String FIELD_TYPE = "type"; + private static final String FIELD_NAME = "name"; + private static final String FIELD_KEY = "key"; + private static final String FIELD_URL = "url"; + private static final String FIELD_MEDIA_ID = "media_id"; + private static final String FIELD_ARTICLE_ID = "article_id"; + private static final String FIELD_APP_ID = "appid"; + private static final String FIELD_PAGE_PATH = "pagepath"; + + // 菜单规则字段常量 + private static final String FIELD_TAG_ID = "tag_id"; + private static final String FIELD_SEX = "sex"; + private static final String FIELD_COUNTRY = "country"; + private static final String FIELD_PROVINCE = "province"; + private static final String FIELD_CITY = "city"; + private static final String FIELD_CLIENT_PLATFORM_TYPE = "client_platform_type"; + private static final String FIELD_LANGUAGE = "language"; + @Override public JsonElement serialize(WxMenu menu, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); - JsonArray buttonArray = new JsonArray(); - for (WxMenuButton button : menu.getButtons()) { - JsonObject buttonJson = convertToJson(button); - buttonArray.add(buttonJson); - } - json.add("button", buttonArray); - + Optional.ofNullable(menu.getButtons()) + .ifPresent(buttons -> buttons.stream() + .map(this::convertToJson) + .forEach(buttonArray::add)); + json.add(FIELD_BUTTON, buttonArray); if (menu.getMatchRule() != null) { - json.add("matchrule", convertToJson(menu.getMatchRule())); + json.add(FIELD_MATCH_RULE, convertToJson(menu.getMatchRule())); } - return json; } protected JsonObject convertToJson(WxMenuButton button) { JsonObject buttonJson = new JsonObject(); - buttonJson.addProperty("type", button.getType()); - buttonJson.addProperty("name", button.getName()); - buttonJson.addProperty("key", button.getKey()); - buttonJson.addProperty("url", button.getUrl()); - buttonJson.addProperty("media_id", button.getMediaId()); - buttonJson.addProperty("article_id", button.getArticleId()); - buttonJson.addProperty("appid", button.getAppId()); - buttonJson.addProperty("pagepath", button.getPagePath()); + addPropertyIfNotNull(buttonJson, FIELD_TYPE, button.getType()); + addPropertyIfNotNull(buttonJson, FIELD_NAME, button.getName()); + addPropertyIfNotNull(buttonJson, FIELD_KEY, button.getKey()); + addPropertyIfNotNull(buttonJson, FIELD_URL, button.getUrl()); + addPropertyIfNotNull(buttonJson, FIELD_MEDIA_ID, button.getMediaId()); + addPropertyIfNotNull(buttonJson, FIELD_ARTICLE_ID, button.getArticleId()); + addPropertyIfNotNull(buttonJson, FIELD_APP_ID, button.getAppId()); + addPropertyIfNotNull(buttonJson, FIELD_PAGE_PATH, button.getPagePath()); if (button.getSubButtons() != null && !button.getSubButtons().isEmpty()) { JsonArray buttonArray = new JsonArray(); - for (WxMenuButton sub_button : button.getSubButtons()) { - buttonArray.add(convertToJson(sub_button)); - } - buttonJson.add("sub_button", buttonArray); + button.getSubButtons().stream() + .map(this::convertToJson) + .forEach(buttonArray::add); + buttonJson.add(FIELD_SUB_BUTTON, buttonArray); } return buttonJson; } protected JsonObject convertToJson(WxMenuRule menuRule) { JsonObject matchRule = new JsonObject(); - matchRule.addProperty("tag_id", menuRule.getTagId()); - matchRule.addProperty("sex", menuRule.getSex()); - matchRule.addProperty("country", menuRule.getCountry()); - matchRule.addProperty("province", menuRule.getProvince()); - matchRule.addProperty("city", menuRule.getCity()); - matchRule.addProperty("client_platform_type", menuRule.getClientPlatformType()); - matchRule.addProperty("language", menuRule.getLanguage()); + addPropertyIfNotNull(matchRule, FIELD_TAG_ID, menuRule.getTagId()); + addPropertyIfNotNull(matchRule, FIELD_SEX, menuRule.getSex()); + addPropertyIfNotNull(matchRule, FIELD_COUNTRY, menuRule.getCountry()); + addPropertyIfNotNull(matchRule, FIELD_PROVINCE, menuRule.getProvince()); + addPropertyIfNotNull(matchRule, FIELD_CITY, menuRule.getCity()); + addPropertyIfNotNull(matchRule, FIELD_CLIENT_PLATFORM_TYPE, menuRule.getClientPlatformType()); + addPropertyIfNotNull(matchRule, FIELD_LANGUAGE, menuRule.getLanguage()); return matchRule; } - @Deprecated - private WxMenuRule convertToRule(JsonObject json) { - WxMenuRule menuRule = new WxMenuRule(); - //变态的微信接口,这里居然反人类的使用和序列化时不一样的名字 - //menuRule.setTagId(GsonHelper.getString(json,"tag_id")); - menuRule.setTagId(GsonHelper.getString(json, "group_id")); - menuRule.setSex(GsonHelper.getString(json, "sex")); - menuRule.setCountry(GsonHelper.getString(json, "country")); - menuRule.setProvince(GsonHelper.getString(json, "province")); - menuRule.setCity(GsonHelper.getString(json, "city")); - menuRule.setClientPlatformType(GsonHelper.getString(json, "client_platform_type")); - menuRule.setLanguage(GsonHelper.getString(json, "language")); - return menuRule; + private void addPropertyIfNotNull(JsonObject obj, String key, String value) { + if (value != null) { + obj.addProperty(key, value); + } } @Override public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - /* - * 操蛋的微信 - * 创建菜单时是 { button : ... } - * 查询菜单时是 { menu : { button : ... } } - * 现在企业号升级为企业微信后,没有此问题,因此需要单独处理 - */ - JsonArray buttonsJson = json.getAsJsonObject().get("menu").getAsJsonObject().get("button").getAsJsonArray(); - return this.buildMenuFromJson(buttonsJson); + JsonObject root = json.getAsJsonObject(); + JsonArray buttonsJson = null; + if (root.has(FIELD_MENU)) { + JsonObject menuObj = root.getAsJsonObject(FIELD_MENU); + buttonsJson = menuObj.getAsJsonArray(FIELD_BUTTON); + } else if (root.has(FIELD_BUTTON)) { + buttonsJson = root.getAsJsonArray(FIELD_BUTTON); + } + if (buttonsJson == null) { + throw new JsonParseException("No button array found in menu JSON"); + } + return buildMenuFromJson(buttonsJson); } protected WxMenu buildMenuFromJson(JsonArray buttonsJson) { WxMenu menu = new WxMenu(); - for (int i = 0; i < buttonsJson.size(); i++) { - JsonObject buttonJson = buttonsJson.get(i).getAsJsonObject(); + for (JsonElement btnElem : buttonsJson) { + JsonObject buttonJson = btnElem.getAsJsonObject(); WxMenuButton button = convertFromJson(buttonJson); menu.getButtons().add(button); - if (buttonJson.get("sub_button") == null || buttonJson.get("sub_button").isJsonNull()) { - continue; - } - JsonArray sub_buttonsJson = buttonJson.get("sub_button").getAsJsonArray(); - for (int j = 0; j < sub_buttonsJson.size(); j++) { - JsonObject sub_buttonJson = sub_buttonsJson.get(j).getAsJsonObject(); - button.getSubButtons().add(convertFromJson(sub_buttonJson)); + if (buttonJson.has(FIELD_SUB_BUTTON) && buttonJson.get(FIELD_SUB_BUTTON).isJsonArray()) { + JsonArray sub_buttonsJson = buttonJson.getAsJsonArray(FIELD_SUB_BUTTON); + for (JsonElement subBtnElem : sub_buttonsJson) { + button.getSubButtons().add(convertFromJson(subBtnElem.getAsJsonObject())); + } } } return menu; @@ -118,14 +126,14 @@ public class WxMenuGsonAdapter implements JsonSerializer, JsonDeserializ protected WxMenuButton convertFromJson(JsonObject json) { WxMenuButton button = new WxMenuButton(); - button.setName(GsonHelper.getString(json, "name")); - button.setKey(GsonHelper.getString(json, "key")); - button.setUrl(GsonHelper.getString(json, "url")); - button.setType(GsonHelper.getString(json, "type")); - button.setMediaId(GsonHelper.getString(json, "media_id")); - button.setArticleId(GsonHelper.getString(json, "article_id")); - button.setAppId(GsonHelper.getString(json, "appid")); - button.setPagePath(GsonHelper.getString(json, "pagepath")); + button.setName(GsonHelper.getString(json, FIELD_NAME)); + button.setKey(GsonHelper.getString(json, FIELD_KEY)); + button.setUrl(GsonHelper.getString(json, FIELD_URL)); + button.setType(GsonHelper.getString(json, FIELD_TYPE)); + button.setMediaId(GsonHelper.getString(json, FIELD_MEDIA_ID)); + button.setArticleId(GsonHelper.getString(json, FIELD_ARTICLE_ID)); + button.setAppId(GsonHelper.getString(json, FIELD_APP_ID)); + button.setPagePath(GsonHelper.getString(json, FIELD_PAGE_PATH)); return button; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java index e3a03ffab..0e78465ea 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpChatGsonAdapter.java @@ -1,11 +1,3 @@ -/* - * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. - * - * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended - * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction - * arose from modification of the original source, or other redistribution of this source - * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. - */ package me.chanjar.weixin.cp.util.json; import com.google.gson.*; @@ -23,46 +15,44 @@ import java.util.List; */ public class WxCpChatGsonAdapter implements JsonSerializer, JsonDeserializer { + public static final String FIELD_CHAT_ID = "chatid"; + public static final String FIELD_NAME = "name"; + public static final String FIELD_OWNER = "owner"; + public static final String FIELD_USER_LIST = "userlist"; + @Override public JsonElement serialize(WxCpChat chat, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); - if (chat.getId() != null) { - json.addProperty("chatid", chat.getId()); - } - if (chat.getName() != null) { - json.addProperty("name", chat.getName()); - } - if (chat.getOwner() != null) { - json.addProperty("owner", chat.getOwner()); - } - if (chat.getUsers() != null) { + addPropertyIfNotNull(json, FIELD_CHAT_ID, chat.getId()); + addPropertyIfNotNull(json, FIELD_NAME, chat.getName()); + addPropertyIfNotNull(json, FIELD_OWNER, chat.getOwner()); + if (chat.getUsers() != null && !chat.getUsers().isEmpty()) { JsonArray users = new JsonArray(); - for (String user : chat.getUsers()) { - users.add(user); - } - json.add("userlist", users); + chat.getUsers().forEach(users::add); + json.add(FIELD_USER_LIST, users); } return json; } + private void addPropertyIfNotNull(JsonObject json, String key, String value) { + if (value != null) { + json.addProperty(key, value); + } + } + @Override public WxCpChat deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject chatJson = json.getAsJsonObject(); - WxCpChat chat = new WxCpChat(); chat.setId(GsonHelper.getAsString(chatJson.get("chatid"))); chat.setName(GsonHelper.getAsString(chatJson.get("name"))); chat.setOwner(GsonHelper.getAsString(chatJson.get("owner"))); - JsonArray usersJson = chatJson.getAsJsonArray("userlist"); - if (usersJson != null) { + if (usersJson != null && !usersJson.isEmpty()) { List users = new ArrayList<>(usersJson.size()); + usersJson.forEach(e -> users.add(e.getAsString())); chat.setUsers(users); - for (JsonElement userJson : usersJson) { - users.add(userJson.getAsString()); - } } - return chat; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java index af9344b70..72d367c43 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java @@ -1,11 +1,3 @@ -/* - * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. - * - * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended - * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction - * arose from modification of the original source, or other redistribution of this source - * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. - */ package me.chanjar.weixin.cp.util.json; import com.google.gson.*; @@ -13,6 +5,8 @@ import me.chanjar.weixin.common.util.json.GsonHelper; import me.chanjar.weixin.cp.bean.WxCpDepart; import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Objects; /** * WxCpDepart的gson适配器. @@ -30,60 +24,47 @@ public class WxCpDepartGsonAdapter implements JsonSerializer, JsonDe @Override public JsonElement serialize(WxCpDepart group, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); - if (group.getId() != null) { - json.addProperty(ID, group.getId()); - } - if (group.getName() != null) { - json.addProperty(NAME, group.getName()); - } - if (group.getEnName() != null) { - json.addProperty(EN_NAME, group.getEnName()); - } - if (group.getDepartmentLeader() != null) { + addPropertyIfNotNull(json, ID, group.getId()); + addPropertyIfNotNull(json, NAME, group.getName()); + addPropertyIfNotNull(json, EN_NAME, group.getEnName()); + if (group.getDepartmentLeader() != null && group.getDepartmentLeader().length > 0) { JsonArray jsonArray = new JsonArray(); - for (String department : group.getDepartmentLeader()) { - jsonArray.add(new JsonPrimitive(department)); - } + Arrays.stream(group.getDepartmentLeader()).filter(Objects::nonNull).forEach(jsonArray::add); json.add(DEPARTMENT_LEADER, jsonArray); } - if (group.getParentId() != null) { - json.addProperty(PARENT_ID, group.getParentId()); - } - if (group.getOrder() != null) { - json.addProperty(ORDER, String.valueOf(group.getOrder())); - } + addPropertyIfNotNull(json, PARENT_ID, group.getParentId()); + addPropertyIfNotNull(json, ORDER, group.getOrder()); return json; } + private void addPropertyIfNotNull(JsonObject json, String key, Object value) { + if (value != null) { + if (value instanceof Number) { + json.addProperty(key, (Number) value); + } else { + json.addProperty(key, value.toString()); + } + } + } + @Override public WxCpDepart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxCpDepart depart = new WxCpDepart(); JsonObject departJson = json.getAsJsonObject(); - if (departJson.get(ID) != null && !departJson.get(ID).isJsonNull()) { - depart.setId(GsonHelper.getAsLong(departJson.get(ID))); - } - if (departJson.get(NAME) != null && !departJson.get(NAME).isJsonNull()) { - depart.setName(GsonHelper.getAsString(departJson.get(NAME))); - } - if (departJson.get(EN_NAME) != null && !departJson.get(EN_NAME).isJsonNull()) { - depart.setEnName(GsonHelper.getAsString(departJson.get(EN_NAME))); - } - if (departJson.getAsJsonArray(DEPARTMENT_LEADER) != null && !departJson.get(DEPARTMENT_LEADER).isJsonNull()) { - JsonArray jsonArray = departJson.getAsJsonArray(DEPARTMENT_LEADER); + depart.setId(GsonHelper.getAsLong(departJson.get(ID))); + depart.setName(GsonHelper.getAsString(departJson.get(NAME))); + depart.setEnName(GsonHelper.getAsString(departJson.get(EN_NAME))); + JsonArray jsonArray = departJson.getAsJsonArray(DEPARTMENT_LEADER); + if (jsonArray != null && !jsonArray.isJsonNull()) { String[] departments = new String[jsonArray.size()]; - int i = 0; - for (JsonElement jsonElement : jsonArray) { - departments[i++] = jsonElement.getAsString(); + for (int i = 0; i < jsonArray.size(); i++) { + departments[i] = jsonArray.get(i).getAsString(); } depart.setDepartmentLeader(departments); } - if (departJson.get(ORDER) != null && !departJson.get(ORDER).isJsonNull()) { - depart.setOrder(GsonHelper.getAsLong(departJson.get(ORDER))); - } - if (departJson.get(PARENT_ID) != null && !departJson.get(PARENT_ID).isJsonNull()) { - depart.setParentId(GsonHelper.getAsLong(departJson.get(PARENT_ID))); - } + depart.setOrder(GsonHelper.getAsLong(departJson.get(ORDER))); + depart.setParentId(GsonHelper.getAsLong(departJson.get(PARENT_ID))); return depart; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java index 41a5b7840..2f830f716 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java @@ -1,11 +1,3 @@ -/* - * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. - * - * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended - * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction - * arose from modification of the original source, or other redistribution of this source - * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. - */ package me.chanjar.weixin.cp.util.json; import com.google.gson.*; @@ -21,19 +13,28 @@ import java.lang.reflect.Type; */ public class WxCpTagGsonAdapter implements JsonSerializer, JsonDeserializer { + private static final String TAG_ID = "tagid"; + private static final String TAG_NAME = "tagname"; + @Override public JsonElement serialize(WxCpTag tag, Type typeOfSrc, JsonSerializationContext context) { JsonObject o = new JsonObject(); - o.addProperty("tagid", tag.getId()); - o.addProperty("tagname", tag.getName()); + addPropertyIfNotNull(o, TAG_ID, tag.getId()); + addPropertyIfNotNull(o, TAG_NAME, tag.getName()); return o; } + private void addPropertyIfNotNull(JsonObject obj, String key, String value) { + if (value != null) { + obj.addProperty(key, value); + } + } + @Override public WxCpTag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); - return new WxCpTag(GsonHelper.getString(jsonObject, "tagid"), GsonHelper.getString(jsonObject, "tagname")); + return new WxCpTag(GsonHelper.getString(jsonObject, TAG_ID), GsonHelper.getString(jsonObject, TAG_NAME)); } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java index a477f1bbf..0da35ff7f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java @@ -1,12 +1,3 @@ -/* - * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. - * - * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended - * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction - * arose from modification of the original source, or other redistribution of this source - * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. - */ - package me.chanjar.weixin.cp.util.json; import com.google.gson.*; @@ -15,6 +6,8 @@ import me.chanjar.weixin.cp.bean.Gender; import me.chanjar.weixin.cp.bean.WxCpUser; import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.stream.IntStream; import static me.chanjar.weixin.cp.bean.WxCpUser.*; @@ -31,66 +24,78 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri private static final String DEPARTMENT = "department"; private static final String EXTERNAL_CORP_NAME = "external_corp_name"; private static final String WECHAT_CHANNELS = "wechat_channels"; + private static final String ORDER = "order"; + private static final String POSITIONS = "positions"; + private static final String USER_ID = "userid"; + private static final String NEW_USER_ID = "new_userid"; + private static final String NAME = "name"; + private static final String POSITION = "position"; + private static final String MOBILE = "mobile"; + private static final String GENDER = "gender"; + private static final String EMAIL = "email"; + private static final String BIZ_MAIL = "biz_mail"; + private static final String AVATAR = "avatar"; + private static final String THUMB_AVATAR = "thumb_avatar"; + private static final String ADDRESS = "address"; + private static final String AVATAR_MEDIAID = "avatar_mediaid"; + private static final String STATUS = "status"; + private static final String ENABLE = "enable"; + private static final String ALIAS = "alias"; + private static final String IS_LEADER = "isleader"; + private static final String IS_LEADER_IN_DEPT = "is_leader_in_dept"; + private static final String HIDE_MOBILE = "hide_mobile"; + private static final String ENGLISH_NAME = "english_name"; + private static final String TELEPHONE = "telephone"; + private static final String QR_CODE = "qr_code"; + private static final String TO_INVITE = "to_invite"; + private static final String OPEN_USER_ID = "open_userid"; + private static final String MAIN_DEPARTMENT = "main_department"; + private static final String DIRECT_LEADER = "direct_leader"; + private static final String TYPE = "type"; + private static final String VALUE = "value"; + private static final String TEXT = "text"; + private static final String WEB = "web"; + private static final String MINIPROGRAM = "miniprogram"; + private static final String URL = "url"; + private static final String TITLE = "title"; + private static final String APPID = "appid"; + private static final String PAGE_PATH = "pagepath"; + private static final String ATTRS = "attrs"; + private static final String NICKNAME = "nickname"; @Override public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxCpUser user = new WxCpUser(); - if (o.get(DEPARTMENT) != null) { - JsonArray departJsonArray = o.get(DEPARTMENT).getAsJsonArray(); - Long[] departIds = new Long[departJsonArray.size()]; - int i = 0; - for (JsonElement jsonElement : departJsonArray) { - departIds[i++] = jsonElement.getAsLong(); - } - user.setDepartIds(departIds); - } + user.setDepartIds(parseJsonArrayToLongArray(o, DEPARTMENT)); + user.setOrders(parseJsonArrayToIntegerArray(o, ORDER)); + user.setPositions(parseJsonArrayToStringArray(o, POSITIONS)); - if (o.get("order") != null) { - JsonArray departJsonArray = o.get("order").getAsJsonArray(); - Integer[] orders = new Integer[departJsonArray.size()]; - int i = 0; - for (JsonElement jsonElement : departJsonArray) { - orders[i++] = jsonElement.getAsInt(); - } - user.setOrders(orders); - } - - if (o.get("positions") != null) { - JsonArray positionJsonArray = o.get("positions").getAsJsonArray(); - String[] positions = new String[positionJsonArray.size()]; - int i = 0; - for (JsonElement jsonElement : positionJsonArray) { - positions[i++] = jsonElement.getAsString(); - } - user.setPositions(positions); - } - - user.setUserId(GsonHelper.getString(o, "userid")); - user.setName(GsonHelper.getString(o, "name")); - user.setPosition(GsonHelper.getString(o, "position")); - user.setMobile(GsonHelper.getString(o, "mobile")); - user.setGender(Gender.fromCode(GsonHelper.getString(o, "gender"))); - user.setEmail(GsonHelper.getString(o, "email")); - user.setBizMail(GsonHelper.getString(o, "biz_mail")); - user.setAvatar(GsonHelper.getString(o, "avatar")); - user.setThumbAvatar(GsonHelper.getString(o, "thumb_avatar")); - user.setAddress(GsonHelper.getString(o, "address")); - user.setAvatarMediaId(GsonHelper.getString(o, "avatar_mediaid")); - user.setStatus(GsonHelper.getInteger(o, "status")); - user.setEnable(GsonHelper.getInteger(o, "enable")); - user.setAlias(GsonHelper.getString(o, "alias")); - user.setIsLeader(GsonHelper.getInteger(o, "isleader")); - user.setIsLeaderInDept(GsonHelper.getIntArray(o, "is_leader_in_dept")); - user.setHideMobile(GsonHelper.getInteger(o, "hide_mobile")); - user.setEnglishName(GsonHelper.getString(o, "english_name")); - user.setTelephone(GsonHelper.getString(o, "telephone")); - user.setQrCode(GsonHelper.getString(o, "qr_code")); - user.setToInvite(GsonHelper.getBoolean(o, "to_invite")); - user.setOpenUserId(GsonHelper.getString(o, "open_userid")); - user.setMainDepartment(GsonHelper.getString(o, "main_department")); - user.setDirectLeader(GsonHelper.getStringArray(o, "direct_leader")); + user.setUserId(GsonHelper.getString(o, USER_ID)); + user.setName(GsonHelper.getString(o, NAME)); + user.setPosition(GsonHelper.getString(o, POSITION)); + user.setMobile(GsonHelper.getString(o, MOBILE)); + user.setGender(Gender.fromCode(GsonHelper.getString(o, GENDER))); + user.setEmail(GsonHelper.getString(o, EMAIL)); + user.setBizMail(GsonHelper.getString(o, BIZ_MAIL)); + user.setAvatar(GsonHelper.getString(o, AVATAR)); + user.setThumbAvatar(GsonHelper.getString(o, THUMB_AVATAR)); + user.setAddress(GsonHelper.getString(o, ADDRESS)); + user.setAvatarMediaId(GsonHelper.getString(o, AVATAR_MEDIAID)); + user.setStatus(GsonHelper.getInteger(o, STATUS)); + user.setEnable(GsonHelper.getInteger(o, ENABLE)); + user.setAlias(GsonHelper.getString(o, ALIAS)); + user.setIsLeader(GsonHelper.getInteger(o, IS_LEADER)); + user.setIsLeaderInDept(GsonHelper.getIntArray(o, IS_LEADER_IN_DEPT)); + user.setHideMobile(GsonHelper.getInteger(o, HIDE_MOBILE)); + user.setEnglishName(GsonHelper.getString(o, ENGLISH_NAME)); + user.setTelephone(GsonHelper.getString(o, TELEPHONE)); + user.setQrCode(GsonHelper.getString(o, QR_CODE)); + user.setToInvite(GsonHelper.getBoolean(o, TO_INVITE)); + user.setOpenUserId(GsonHelper.getString(o, OPEN_USER_ID)); + user.setMainDepartment(GsonHelper.getString(o, MAIN_DEPARTMENT)); + user.setDirectLeader(GsonHelper.getStringArray(o, DIRECT_LEADER)); if (GsonHelper.isNotNull(o.get(EXTRA_ATTR))) { this.buildExtraAttrs(o, user); @@ -102,8 +107,9 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri JsonElement jsonElement = o.get(EXTERNAL_PROFILE).getAsJsonObject().get(WECHAT_CHANNELS); if (jsonElement != null) { JsonObject asJsonObject = jsonElement.getAsJsonObject(); - user.setWechatChannels(WechatChannels.builder().nickname(GsonHelper.getString(asJsonObject, "nickname")).status(GsonHelper.getInteger(asJsonObject, "status")).build()); + user.setWechatChannels(WechatChannels.builder().nickname(GsonHelper.getString(asJsonObject, NICKNAME)).status(GsonHelper.getInteger(asJsonObject, STATUS)).build()); } + this.buildExternalAttrs(o, user); } @@ -112,33 +118,66 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri return user; } + private Long[] parseJsonArrayToLongArray(JsonObject o, String key) { + JsonElement element = o.get(key); + if (element == null || !element.isJsonArray()) { + return null; + } + JsonArray jsonArray = element.getAsJsonArray(); + return IntStream.range(0, jsonArray.size()) + .mapToObj(i -> jsonArray.get(i).getAsLong()) + .toArray(Long[]::new); + } + + private Integer[] parseJsonArrayToIntegerArray(JsonObject o, String key) { + JsonElement element = o.get(key); + if (element == null || !element.isJsonArray()) { + return null; + } + JsonArray jsonArray = element.getAsJsonArray(); + return IntStream.range(0, jsonArray.size()) + .mapToObj(i -> jsonArray.get(i).getAsInt()) + .toArray(Integer[]::new); + } + + private String[] parseJsonArrayToStringArray(JsonObject o, String key) { + JsonElement element = o.get(key); + if (element == null || !element.isJsonArray()) { + return null; + } + JsonArray jsonArray = element.getAsJsonArray(); + return IntStream.range(0, jsonArray.size()) + .mapToObj(i -> jsonArray.get(i).getAsString()) + .toArray(String[]::new); + } + private void buildExtraAttrs(JsonObject o, WxCpUser user) { - JsonArray attrJsonElements = o.get(EXTRA_ATTR).getAsJsonObject().get("attrs").getAsJsonArray(); + JsonArray attrJsonElements = o.get(EXTRA_ATTR).getAsJsonObject().get(ATTRS).getAsJsonArray(); for (JsonElement attrJsonElement : attrJsonElements) { - final Integer type = GsonHelper.getInteger(attrJsonElement.getAsJsonObject(), "type"); + final Integer type = GsonHelper.getInteger(attrJsonElement.getAsJsonObject(), TYPE); final Attr attr = new Attr().setType(type) - .setName(GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name")); + .setName(GsonHelper.getString(attrJsonElement.getAsJsonObject(), NAME)); user.getExtAttrs().add(attr); if (type == null) { - attr.setTextValue(GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value")); + attr.setTextValue(GsonHelper.getString(attrJsonElement.getAsJsonObject(), VALUE)); continue; } switch (type) { case 0: { - JsonElement textJsonElement = attrJsonElement.getAsJsonObject().get("text"); + JsonElement textJsonElement = attrJsonElement.getAsJsonObject().get(TEXT); if (textJsonElement != null && !textJsonElement.isJsonNull() && textJsonElement.isJsonObject()) { - attr.setTextValue(GsonHelper.getString(textJsonElement.getAsJsonObject(), "value")); + attr.setTextValue(GsonHelper.getString(textJsonElement.getAsJsonObject(), VALUE)); } else { attr.setTextValue(null); // Clear or set a default value to avoid stale data } break; } case 1: { - final JsonObject web = attrJsonElement.getAsJsonObject().get("web").getAsJsonObject(); - attr.setWebTitle(GsonHelper.getString(web, "title")) - .setWebUrl(GsonHelper.getString(web, "url")); + final JsonObject web = attrJsonElement.getAsJsonObject().get(WEB).getAsJsonObject(); + attr.setWebTitle(GsonHelper.getString(web, TITLE)) + .setWebUrl(GsonHelper.getString(web, URL)); break; } default://ignored @@ -154,8 +193,8 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri JsonArray attrJsonElements = jsonElement.getAsJsonArray(); for (JsonElement element : attrJsonElements) { - final Integer type = GsonHelper.getInteger(element.getAsJsonObject(), "type"); - final String name = GsonHelper.getString(element.getAsJsonObject(), "name"); + final Integer type = GsonHelper.getInteger(element.getAsJsonObject(), TYPE); + final String name = GsonHelper.getString(element.getAsJsonObject(), NAME); if (type == null) { continue; @@ -167,32 +206,32 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri .add(ExternalAttribute.builder() .type(type) .name(name) - .value(GsonHelper.getString(element.getAsJsonObject().get("text").getAsJsonObject(), "value")) + .value(GsonHelper.getString(element.getAsJsonObject().get(TEXT).getAsJsonObject(), VALUE)) .build() ); break; } case 1: { - final JsonObject web = element.getAsJsonObject().get("web").getAsJsonObject(); + final JsonObject web = element.getAsJsonObject().get(WEB).getAsJsonObject(); user.getExternalAttrs() .add(ExternalAttribute.builder() .type(type) .name(name) - .url(GsonHelper.getString(web, "url")) - .title(GsonHelper.getString(web, "title")) + .url(GsonHelper.getString(web, URL)) + .title(GsonHelper.getString(web, TITLE)) .build() ); break; } case 2: { - final JsonObject miniprogram = element.getAsJsonObject().get("miniprogram").getAsJsonObject(); + final JsonObject miniprogram = element.getAsJsonObject().get(MINIPROGRAM).getAsJsonObject(); user.getExternalAttrs() .add(ExternalAttribute.builder() .type(type) .name(name) - .appid(GsonHelper.getString(miniprogram, "appid")) - .pagePath(GsonHelper.getString(miniprogram, "pagepath")) - .title(GsonHelper.getString(miniprogram, "title")) + .appid(GsonHelper.getString(miniprogram, APPID)) + .pagePath(GsonHelper.getString(miniprogram, PAGE_PATH)) + .title(GsonHelper.getString(miniprogram, TITLE)) .build() ); break; @@ -205,97 +244,70 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri @Override public JsonElement serialize(WxCpUser user, Type typeOfSrc, JsonSerializationContext context) { JsonObject o = new JsonObject(); - this.addProperty(o, "userid", user.getUserId()); - this.addProperty(o, "new_userid", user.getNewUserId()); - this.addProperty(o, "name", user.getName()); - if (user.getDepartIds() != null) { - JsonArray jsonArray = new JsonArray(); - for (Long departId : user.getDepartIds()) { - jsonArray.add(new JsonPrimitive(departId)); - } - o.add("department", jsonArray); - } + addProperty(o, USER_ID, user.getUserId()); + addProperty(o, NEW_USER_ID, user.getNewUserId()); + addProperty(o, NAME, user.getName()); - if (user.getOrders() != null) { - JsonArray jsonArray = new JsonArray(); - for (Integer order : user.getOrders()) { - jsonArray.add(new JsonPrimitive(order)); - } - o.add("order", jsonArray); - } + addArrayProperty(o, DEPARTMENT, user.getDepartIds()); + addArrayProperty(o, ORDER, user.getOrders()); + addProperty(o, POSITION, user.getPosition()); + addArrayProperty(o, POSITIONS, user.getPositions()); - this.addProperty(o, "position", user.getPosition()); - - if (user.getPositions() != null) { - JsonArray jsonArray = new JsonArray(); - for (String position : user.getPositions()) { - jsonArray.add(new JsonPrimitive(position)); - } - o.add("positions", jsonArray); - } - - this.addProperty(o, "mobile", user.getMobile()); + addProperty(o, MOBILE, user.getMobile()); if (user.getGender() != null) { - o.addProperty("gender", user.getGender().getCode()); + o.addProperty(GENDER, user.getGender().getCode()); } - this.addProperty(o, "email", user.getEmail()); - this.addProperty(o, "biz_mail", user.getBizMail()); - this.addProperty(o, "avatar", user.getAvatar()); - this.addProperty(o, "thumb_avatar", user.getThumbAvatar()); - this.addProperty(o, "address", user.getAddress()); - this.addProperty(o, "avatar_mediaid", user.getAvatarMediaId()); - this.addProperty(o, "status", user.getStatus()); - this.addProperty(o, "enable", user.getEnable()); - this.addProperty(o, "alias", user.getAlias()); - this.addProperty(o, "isleader", user.getIsLeader()); + addProperty(o, EMAIL, user.getEmail()); + addProperty(o, BIZ_MAIL, user.getBizMail()); + addProperty(o, AVATAR, user.getAvatar()); + addProperty(o, THUMB_AVATAR, user.getThumbAvatar()); + addProperty(o, ADDRESS, user.getAddress()); + addProperty(o, AVATAR_MEDIAID, user.getAvatarMediaId()); + addProperty(o, STATUS, user.getStatus()); + addProperty(o, ENABLE, user.getEnable()); + addProperty(o, ALIAS, user.getAlias()); + addProperty(o, IS_LEADER, user.getIsLeader()); if (user.getIsLeaderInDept() != null && user.getIsLeaderInDept().length > 0) { JsonArray ary = new JsonArray(); - for (int item : user.getIsLeaderInDept()) { - ary.add(item); - } - o.add("is_leader_in_dept", ary); + Arrays.stream(user.getIsLeaderInDept()).forEach(ary::add); + o.add(IS_LEADER_IN_DEPT, ary); } - this.addProperty(o, "hide_mobile", user.getHideMobile()); - this.addProperty(o, "english_name", user.getEnglishName()); - this.addProperty(o, "telephone", user.getTelephone()); - this.addProperty(o, "qr_code", user.getQrCode()); + addProperty(o, HIDE_MOBILE, user.getHideMobile()); + addProperty(o, ENGLISH_NAME, user.getEnglishName()); + addProperty(o, TELEPHONE, user.getTelephone()); + addProperty(o, QR_CODE, user.getQrCode()); if (user.getToInvite() != null) { - o.addProperty("to_invite", user.getToInvite()); + o.addProperty(TO_INVITE, user.getToInvite()); } - this.addProperty(o, "main_department", user.getMainDepartment()); + addProperty(o, MAIN_DEPARTMENT, user.getMainDepartment()); + + addArrayProperty(o, DIRECT_LEADER, user.getDirectLeader()); - if (user.getDirectLeader() != null && user.getDirectLeader().length > 0) { - JsonArray ary = new JsonArray(); - for (String item : user.getDirectLeader()) { - ary.add(item); - } - o.add("direct_leader", ary); - } if (!user.getExtAttrs().isEmpty()) { JsonArray attrsJsonArray = new JsonArray(); for (Attr attr : user.getExtAttrs()) { - JsonObject attrJson = GsonHelper.buildJsonObject("type", attr.getType(), - "name", attr.getName()); + JsonObject attrJson = GsonHelper.buildJsonObject(TYPE, attr.getType(), + NAME, attr.getName()); attrsJsonArray.add(attrJson); if (attr.getType() == null) { - attrJson.addProperty("name", attr.getName()); - attrJson.addProperty("value", attr.getTextValue()); + attrJson.addProperty(NAME, attr.getName()); + attrJson.addProperty(VALUE, attr.getTextValue()); continue; } switch (attr.getType()) { case 0: - attrJson.add("text", GsonHelper.buildJsonObject("value", attr.getTextValue())); + attrJson.add(TEXT, GsonHelper.buildJsonObject(VALUE, attr.getTextValue())); break; case 1: - attrJson.add("web", GsonHelper.buildJsonObject("url", attr.getWebUrl(), "title", attr.getWebTitle())); + attrJson.add(WEB, GsonHelper.buildJsonObject(URL, attr.getWebUrl(), TITLE, attr.getWebTitle())); break; default: //ignored } } JsonObject attrsJson = new JsonObject(); - attrsJson.add("attrs", attrsJsonArray); + attrsJson.add(ATTRS, attrsJsonArray); o.add(EXTRA_ATTR, attrsJson); } @@ -307,15 +319,15 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri this.addProperty(attrsJson, EXTERNAL_CORP_NAME, user.getExternalCorpName()); if (user.getWechatChannels() != null) { - attrsJson.add(WECHAT_CHANNELS, GsonHelper.buildJsonObject("nickname", user.getWechatChannels().getNickname(), - "status", user.getWechatChannels().getStatus())); + attrsJson.add(WECHAT_CHANNELS, GsonHelper.buildJsonObject(NICKNAME, user.getWechatChannels().getNickname(), + STATUS, user.getWechatChannels().getStatus())); } if (!user.getExternalAttrs().isEmpty()) { JsonArray attrsJsonArray = new JsonArray(); for (ExternalAttribute attr : user.getExternalAttrs()) { - JsonObject attrJson = GsonHelper.buildJsonObject("type", attr.getType(), - "name", attr.getName()); + JsonObject attrJson = GsonHelper.buildJsonObject(TYPE, attr.getType(), + NAME, attr.getName()); attrsJsonArray.add(attrJson); @@ -325,14 +337,14 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri switch (attr.getType()) { case 0: - attrJson.add("text", GsonHelper.buildJsonObject("value", attr.getValue())); + attrJson.add(TEXT, GsonHelper.buildJsonObject(VALUE, attr.getValue())); break; case 1: - attrJson.add("web", GsonHelper.buildJsonObject("url", attr.getUrl(), "title", attr.getTitle())); + attrJson.add(WEB, GsonHelper.buildJsonObject(URL, attr.getUrl(), TITLE, attr.getTitle())); break; case 2: - attrJson.add("miniprogram", GsonHelper.buildJsonObject("appid", attr.getAppid(), - "pagepath", attr.getPagePath(), "title", attr.getTitle())); + attrJson.add(MINIPROGRAM, GsonHelper.buildJsonObject(APPID, attr.getAppid(), + PAGE_PATH, attr.getPagePath(), TITLE, attr.getTitle())); break; default://忽略 } @@ -344,15 +356,29 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri return o; } - private void addProperty(JsonObject object, String property, Integer value) { - if (value != null) { - object.addProperty(property, value); + private void addArrayProperty(JsonObject o, String key, Object[] array) { + if (array != null && array.length > 0) { + JsonArray jsonArray = new JsonArray(); + Arrays.stream(array).forEach(item -> { + if (item instanceof Number) { + jsonArray.add((Number) item); + } else { + jsonArray.add(item.toString()); + } + }); + o.add(key, jsonArray); } } - private void addProperty(JsonObject object, String property, String value) { + private void addProperty(JsonObject object, String property, Object value) { if (value != null) { - object.addProperty(property, value); + if (value instanceof Number) { + object.addProperty(property, (Number) value); + } else if (value instanceof Boolean) { + object.addProperty(property, (Boolean) value); + } else { + object.addProperty(property, value.toString()); + } } }