json-flattener icon indicating copy to clipboard operation
json-flattener copied to clipboard

JsonUnflattener.unflatten() throws error for "" key in json

Open kridai opened this issue 4 months ago • 0 comments

When trying to flatten and unflatten a json containing "" (empty) string as key in json the JsonUnflattener.unflatten() throws an error

Sample code

void testJsonUnflatten() {
        String json = """
            {
              "item_list": [
                {
                  "": 67,
                  "val": 6
                }
              ]
            }
            """;
        ObjectMapper objectMapper = new ObjectMapper();
        var jacksonJsonCore = new JacksonJsonCore(objectMapper);
        Map<String, Object> flattenedResponse =
          new JsonFlattener(jacksonJsonCore, json).flattenAsMap();
        try {
            String unflattenedJson = new JsonUnflattener(jacksonJsonCore, flattenedResponse).unflatten();
            System.out.println(unflattenedJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The error thrown

java.lang.ClassCastException: class com.fasterxml.jackson.databind.node.IntNode cannot be cast to class com.fasterxml.jackson.databind.node.ObjectNode (com.fasterxml.jackson.databind.node.IntNode and com.fasterxml.jackson.databind.node.ObjectNode are in unnamed module of loader 'app')
	at com.github.wnameless.json.base.JacksonJsonValue.asObject(JacksonJsonValue.java:74)
	at com.github.wnameless.json.base.JacksonJsonValue.asObject(JacksonJsonValue.java:33)
	at com.github.wnameless.json.unflattener.JsonUnflattener.findOrCreateJsonObject(JsonUnflattener.java:514)
	at com.github.wnameless.json.unflattener.JsonUnflattener.unflatten(JsonUnflattener.java:378)
	at .testJsonUnflatten(SchemalessResponseObjectTest.java:55)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)

kridai avatar Oct 22 '24 06:10 kridai