You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hugegraph.apache.org by ji...@apache.org on 2026/10/13 04:30:50 UTC

(hugegraph-toolchain) branch master updated: chore: added method to parse json list (#577)

This is an automated email from the ASF dual-hosted git repository.

imbajin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hugegraph-toolchain.git


The following commit(s) were added to refs/heads/master by this push:
     new 8e6ed8477 chore: added method to parse json list (#577)
8e6ed8477 is described below

commit 8e6ed84777387a586f13d713568b11a654d8d1fa
Author: diaohancai <36...@users.noreply.github.com>
AuthorDate: Tue Oct 13 12:30:45 2026 +0800

    chore: added method to parse json list (#577)
    
    Co-authored-by: imbajin <ji...@apache.org>
---
 hugegraph-client/README.md                         |  10 ++
 .../java/org/apache/hugegraph/util/JsonUtil.java   |  16 +++
 .../org/apache/hugegraph/unit/JsonUtilTest.java    | 142 +++++++++++++++++++++
 .../org/apache/hugegraph/unit/UnitTestSuite.java   |   3 +-
 4 files changed, 170 insertions(+), 1 deletion(-)

diff --git a/hugegraph-client/README.md b/hugegraph-client/README.md
index 004f112c2..af9299232 100644
--- a/hugegraph-client/README.md
+++ b/hugegraph-client/README.md
@@ -15,6 +15,16 @@ hugegraph-client is a Java-written client of [HugeGraph](https://github.com/apac
 - RESTful Traversals, shortest path, k-out, k-neighbor, paths and crosspoints etc.
 - Variables, CRUD of variables
 
+## JSON lists
+
+`JsonUtil.fromJson2List(json, Element.class)` deserializes a JSON array into a
+`List<Element>` using the client's shared Jackson mapper. For example,
+`JsonUtil.fromJson2List("[1, 2]", Integer.class)` returns a list of integers.
+An empty array returns an empty list, JSON `null` returns Java `null`, and null
+array elements are preserved. A null input string throws `IllegalArgumentException`;
+malformed JSON, non-array input, or incompatible element values throw
+`SerializeException` with the original Jackson exception as the cause.
+
 ## Doc
 
 The [client homepage](https://hugegraph.apache.org/docs/quickstart/hugegraph-client/) contains more information about it.
diff --git a/hugegraph-client/src/main/java/org/apache/hugegraph/util/JsonUtil.java b/hugegraph-client/src/main/java/org/apache/hugegraph/util/JsonUtil.java
index 8222fdea8..45f0e8bd1 100644
--- a/hugegraph-client/src/main/java/org/apache/hugegraph/util/JsonUtil.java
+++ b/hugegraph-client/src/main/java/org/apache/hugegraph/util/JsonUtil.java
@@ -18,6 +18,7 @@
 package org.apache.hugegraph.util;
 
 import java.io.IOException;
+import java.util.List;
 
 import org.apache.hugegraph.rest.SerializeException;
 
@@ -60,4 +61,19 @@ public final class JsonUtil {
                                          e, node);
         }
     }
+
+    /**
+     * Deserialize a JSON array into a list of the requested element type.
+     * JSON null returns null; a null input string throws IllegalArgumentException.
+     * Invalid JSON or incompatible elements throw SerializeException.
+     */
+    public static <T> List<T> fromJson2List(String json, Class<T> clazz) {
+        try {
+            return MAPPER.readValue(json, MAPPER.getTypeFactory()
+                                               .constructCollectionType(List.class, clazz));
+        } catch (IOException e) {
+            throw new SerializeException("Failed to deserialize json '%s'",
+                                         e, json);
+        }
+    }
 }
diff --git a/hugegraph-client/src/test/java/org/apache/hugegraph/unit/JsonUtilTest.java b/hugegraph-client/src/test/java/org/apache/hugegraph/unit/JsonUtilTest.java
new file mode 100644
index 000000000..9dbc222c8
--- /dev/null
+++ b/hugegraph-client/src/test/java/org/apache/hugegraph/unit/JsonUtilTest.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.hugegraph.unit;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import org.apache.hugegraph.rest.SerializeException;
+import org.apache.hugegraph.util.JsonUtil;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class JsonUtilTest {
+
+    @Test
+    public void testToJson() {
+        Cat cat = new Cat();
+        cat.setName("alice");
+        cat.setAge(7);
+        Assert.assertEquals("{\"name\":\"alice\",\"age\":7}", JsonUtil.toJson(cat));
+    }
+
+    @Test
+    public void testFromJson() {
+        Cat cat = JsonUtil.fromJson("{\"name\":\"alice\",\"age\":7}", Cat.class);
+        Assert.assertEquals("alice", cat.getName());
+        Assert.assertEquals(Integer.valueOf(7), cat.getAge());
+    }
+
+    @Test
+    public void testConvertValue() throws IOException {
+        Cat cat = JsonUtil.convertValue(new ObjectMapper().readTree(
+                "{\"name\":\"alice\",\"age\":7}"), Cat.class);
+        Assert.assertEquals("alice", cat.getName());
+        Assert.assertEquals(Integer.valueOf(7), cat.getAge());
+    }
+
+    @Test
+    public void testFromJson2ListWithPojo() {
+        List<Cat> cats = JsonUtil.fromJson2List("[{\"name\":\"alice\",\"age\":7}]", Cat.class);
+        Assert.assertEquals(1, cats.size());
+        Assert.assertEquals(Cat.class, cats.get(0).getClass());
+        Assert.assertEquals("alice", cats.get(0).getName());
+        Assert.assertEquals(Integer.valueOf(7), cats.get(0).getAge());
+        Cat expected = new Cat();
+        expected.setName("alice");
+        expected.setAge(7);
+        Assert.assertEquals(expected, cats.get(0));
+        Assert.assertEquals(expected.hashCode(), cats.get(0).hashCode());
+    }
+
+    @Test
+    public void testFromJson2ListWithEmptyAndNull() {
+        Assert.assertEquals(Collections.emptyList(), JsonUtil.fromJson2List("[]", Cat.class));
+        Assert.assertNull(JsonUtil.fromJson2List("null", Cat.class));
+        Assert.assertEquals(Collections.singletonList(null),
+                            JsonUtil.fromJson2List("[null]", Cat.class));
+        try {
+            JsonUtil.fromJson2List(null, Cat.class);
+            Assert.fail("Expected IllegalArgumentException for null input");
+        } catch (IllegalArgumentException expected) {
+            // Match ObjectMapper and fromJson null-input behavior.
+        }
+    }
+
+    @Test
+    public void testFromJson2ListWithInvalidInput() {
+        String[] invalid = {"", "   ", "[{", "{\"name\":\"alice\",\"age\":7}",
+                            "\"alice\"", "7", "true", "[\"wrong\"]",
+                            "[{\"name\":\"alice\",\"age\":\"not-an-int\"}]"};
+        for (String json : invalid) {
+            try {
+                JsonUtil.fromJson2List(json, Cat.class);
+                Assert.fail("Expected SerializeException for: " + json);
+            } catch (SerializeException exception) {
+                Assert.assertTrue(exception.getCause() instanceof IOException);
+                Assert.assertTrue(exception.getMessage().contains(json));
+            }
+        }
+    }
+
+    public static class Cat {
+
+        private String name;
+        private Integer age;
+
+        public Cat() {
+        }
+
+        public String getName() {
+            return this.name;
+        }
+
+        public void setName(String name) {
+            this.name = name;
+        }
+
+        public Integer getAge() {
+            return this.age;
+        }
+
+        public void setAge(Integer age) {
+            this.age = age;
+        }
+
+        @Override
+        public boolean equals(Object object) {
+            if (this == object) {
+                return true;
+            }
+            if (!(object instanceof Cat)) {
+                return false;
+            }
+            Cat other = (Cat) object;
+            return Objects.equals(this.name, other.name) && Objects.equals(this.age, other.age);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(this.name, this.age);
+        }
+    }
+}
diff --git a/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java b/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
index 97c32fc1e..5be7d90bf 100644
--- a/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
+++ b/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
@@ -40,7 +40,8 @@ import org.junit.runners.Suite;
         ServerCompatibilityTest.class,
         CommonUtilTest.class,
         IdUtilTest.class,
-        SplicingIdGeneratorTest.class
+        SplicingIdGeneratorTest.class,
+        JsonUtilTest.class
 })
 public class UnitTestSuite {
 }