From 05a5c5b77dab8bb474ea4422a31711c9fa18ee99 Mon Sep 17 00:00:00 2001 From: lilanlong <356105485@qq.com> Date: Tue, 23 Jul 2024 13:48:01 +0800 Subject: [PATCH] feat: JSON Object of method adds dynamic parameters (#2824) * feat: JSON Object of method adds dynamic parameters * Add unit testing --- .../com/alibaba/fastjson2/JSONObject.java | 83 +++++++++++++++++++ .../alibaba/fastjson2/JSONObjectTest3.java | 2 + 2 files changed, 85 insertions(+) diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONObject.java b/core/src/main/java/com/alibaba/fastjson2/JSONObject.java index b5317fd233..eff470fffe 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONObject.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONObject.java @@ -23,6 +23,8 @@ import java.util.*; import java.util.function.Consumer; import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static com.alibaba.fastjson2.JSONWriter.Feature.*; import static com.alibaba.fastjson2.util.BeanUtils.getAnnotations; @@ -2017,6 +2019,87 @@ public static JSONObject of( return object; } + /** + * Pack multiple key-value pairs as {@link JSONObject} + * + *
+ * JSONObject jsonObject = JSONObject.of("key1", "value1", "key2", "value2", "key3", "value3", "key4", "value4", "key5", "value5", kvArray); + *+ * + * @param k1 first key + * @param v1 first value + * @param k2 second key + * @param v2 second value + * @param k3 third key + * @param v3 third value + * @param k4 four key + * @param v4 four value + * @param k5 five key + * @param v5 five value + * @param kvArray multiple key-value + * @since 2.0.53 + */ + public static JSONObject of( + String k1, + Object v1, + String k2, + Object v2, + String k3, + Object v3, + String k4, + Object v4, + String k5, + Object v5, + Object... kvArray + + ) { + JSONObject object = new JSONObject(5); + object.put(k1, v1); + object.put(k2, v2); + object.put(k3, v3); + object.put(k4, v4); + object.put(k5, v5); + if (kvArray != null && kvArray.length > 0) { + of(object, kvArray); + } + return object; + } + + /** + * Pack multiple key-value pairs as {@link JSONObject} + * + *
+ * JSONObject jsonObject = JSONObject.of(Object... kvArray); + *+ * + * @param kvArray key-value + * @since 2.0.53 + */ + private static JSONObject of(JSONObject object, Object... kvArray) { + if (kvArray == null || kvArray.length <= 0) { + throw new JSONException("The kvArray cannot be empty"); + } + int kvArrayLength = kvArray.length; + if ((kvArrayLength & 1) == 1) { + throw new JSONException("The length of kvArray cannot be odd"); + } + List