From 72fae1753f2a4a01bf7121dfc21e817b39184f33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AB=98=E9=93=81?= Date: Tue, 9 Jul 2024 08:26:34 +0800 Subject: [PATCH] getLong support boolean --- core/src/main/java/com/alibaba/fastjson2/JSONArray.java | 4 ++++ core/src/main/java/com/alibaba/fastjson2/JSONObject.java | 4 ++++ .../java/com/alibaba/fastjson2/issues_2700/Issue2745.java | 2 ++ 3 files changed, 10 insertions(+) diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONArray.java b/core/src/main/java/com/alibaba/fastjson2/JSONArray.java index 6b46fa5026..9da34e6339 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONArray.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONArray.java @@ -421,6 +421,10 @@ public Long getLong(int index) { return Long.parseLong(str); } + if (value instanceof Boolean) { + return (boolean) value ? Long.valueOf(1) : Long.valueOf(0); + } + throw new JSONException("Can not cast '" + value.getClass() + "' to Long"); } diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONObject.java b/core/src/main/java/com/alibaba/fastjson2/JSONObject.java index 4321892c69..b5317fd233 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONObject.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONObject.java @@ -524,6 +524,10 @@ public Long getLong(String key) { return Long.parseLong(str); } + if (value instanceof Boolean) { + return (boolean) value ? Long.valueOf(1) : Long.valueOf(0); + } + throw new JSONException("Can not cast '" + value.getClass() + "' to Long"); } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_2700/Issue2745.java b/core/src/test/java/com/alibaba/fastjson2/issues_2700/Issue2745.java index 1b430572a4..0d0281230a 100644 --- a/core/src/test/java/com/alibaba/fastjson2/issues_2700/Issue2745.java +++ b/core/src/test/java/com/alibaba/fastjson2/issues_2700/Issue2745.java @@ -17,6 +17,7 @@ public void Test1() throws Exception { assertEquals(BigDecimal.ONE, jsonArray.getBigDecimal(0)); assertEquals(BigInteger.ONE, jsonArray.getBigInteger(0)); assertEquals(Integer.valueOf(1), jsonArray.getInteger(0)); + assertEquals(Long.valueOf(1), jsonArray.getLong(0)); } @Test @@ -26,5 +27,6 @@ public void Test2() throws Exception { assertEquals(BigDecimal.ONE, obj.getBigDecimal("bool")); assertEquals(BigInteger.ONE, obj.getBigInteger("bool")); assertEquals(Integer.valueOf(1), obj.getInteger("bool")); + assertEquals(Long.valueOf(1), obj.getLong("bool")); } }