mardi 30 juin 2015

Call method with parameters through JSON in Java

I am receiving JSON messages from an API (I have full control of the messages sent). The messages look like this :

{
 "function": "function_name",
 "arguments": { "arg1": "Value", "arg2": "Value"}
}

I want to use reflection to call the right method with the right parameters and in the right order. The problem with that code is that the JSONObject conversion of the arguments doesn't keep the order of the parameters (which is normal given that JSON is, by definition, unordered). What I would need is some kind of mapping with the parameters name.

Here is my Java code :

    String function_name = (String)json.get("function");

    ArrayList<Class> params = new ArrayList<Class>();
    ArrayList<String> values = new ArrayList<String>();

    JSONObject args = (JSONObject)json.get("arguments");


    if (args != null) {
        Set<String> keysargs = args.keySet();
        for (String key : keysargs) {

            params.add(args.get(key).getClass());
            values.add(args.get(key).toString());
        }
    }

    Method method;
    try {
      if (params.size() == 0) {
          method = this.getApplication().getClass().getMethod(function_name);
      }
      else {
          method = this.getApplication().getClass().getMethod(function_name, params.toArray(new Class[params.size()]));
      }

      try {
        method.invoke(this.getApplication(), values.toArray());
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }





Aucun commentaire:

Enregistrer un commentaire