0

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?

SonMooSans
  • 95
  • 1
  • 4
  • There is not enough detail here, please show us what you've tried and define your issue more clearly. – Igor Flakiewicz Jan 20 '22 at 10:31
  • I added some codes, maybe it can help you to understand what I am doing – SonMooSans Jan 20 '22 at 10:41
  • Why not just map it to an Object list and then cast the objects into your specific types? – Igor Flakiewicz Jan 20 '22 at 10:52
  • It will throw ClassCastException when deserializing json inside the array As it is a LinkedHashMap – SonMooSans Jan 20 '22 at 10:56
  • Check out this question https://stackoverflow.com/questions/26526030/how-do-you-tree-walk-json-via-jackson-2-jsonnode , I think you can crawl the json structure as described here and conditionally call your method at whatever specific points you need to. – Igor Flakiewicz Jan 20 '22 at 13:59

0 Answers0