2 years ago

#74132

test-img

SonMooSans

Jackson deserialize json array to method parameters

Input json: ["Test", 0, {name:"Henry", age:12}]

Types in the array are random, I want to map it to parameters of a method

I can get parameter types by using method.getParameterTypes()

I have tried this:

        ObjectMapper mapper = getJsonMapper();

        String[] jsonArg = mapper.readValue(json, String[].class);

        Class<?>[] params = method.getParameterTypes();

        if (jsonArg.length != params.length)
            throw new IllegalArgumentException("Wrong args length");

        Object[] args = new Object[params.length];

        for (int i = 0;i < jsonArg.length;i++) {
            args[i] = mapper.readValue(jsonArg[i], params[i]);
        }

        method.invoke(obj, args); //Invoke Method

And it will throw a JsonMappingException as it isn't a string array

How can I map it to the method parameter?

java

json

jackson

0 Answers

Your Answer

Accepted video resources