Search code examples
javaformsapache-commons-httpclient

Which API to convert Java List<Object> to HTTP Form Parameters?


I have the following java class:

class Foo{
  String param1;
  String param2;
}

I have a List<Foo> myFoos; (JSON pseudocode):

[
 {param1="1_1", param2="1_2"},
 {param1="2_1", param2="2_2"}
]

How do I convert it to the following (encoded) HTTP Form Paramers?

myFoos[0][param1]=1_1
myFoos[0][param2]=1_2
myFoos[1][param1]=2_1
myFoos[1][param2]=2_2

I'm currently using Apache HttpClient 4.5 but can't see an appropriate converter.


Solution

  • You can try something like this:

    public String toFormParams(List<?> items, Class clazz) {
    
        String name = clazz.getSimpleName();
        // Find public/private members
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder sb = new StringBuilder();
    
        for (int i = 0; i < items.size(); i++) {
            Object item = items.get(i)
    
            for (int f = 0; f < fields.length; f++) {
                Field field = fields[f];
                // ensure private members can be accessed
                field.setAccessible(true);
    
                sb.append(name);
                sb.append("[" + i + "]");
                sb.append("[" + field.getName() + "]");
                sb.append("=" + field.get(item));
                sb.append("\n");
            }
        }
    
        // Remove last \n and return
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
    

    Note that I did not test this, and it can be improved.