Ying Yi Ying Yi - 3 months ago 9
Java Question

How to convert javabean to post param string?

example:

public class user{
private String name;
private String age;
private String address;
.... set and get methods....
}

User user = new User();
user.setName("albert");
user.setAge("22");


i want convert user object to this string

name=albert&address=&age=22


Beacuse i use
new URL()
to post this string.

I have much other object to convert to like this string,so i want a tool method

Is any good way to do?

Thanks in advance

Answer

Using reflection for any Object type:

import java.lang.reflect.Field;

public class ObjectToPostStringbyReflection {


    public String getPostParamString(Object o) throws IllegalArgumentException, IllegalAccessException{
        Class<? extends Object> clazz = o.getClass();
        StringBuilder sb = new StringBuilder();
        for(Field f : clazz.getDeclaredFields()){
            f.setAccessible(true);
            if(!sb.toString().isEmpty()){
                sb.append("&");
            }
            sb.append(f.getName())
                .append("=")
                .append(f.get(o));
        }
        return sb.toString();
    }

    /**
     * @param args
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     */
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub
        User user = new User();
        user.setName("John");
        user.setAddress("address");
        user.setAge("18");
        ObjectToPostStringbyReflection reflector = new ObjectToPostStringbyReflection();
        System.out.println(reflector.getPostParamString(user));
    }
}

Result: name=John&age=18&address=address

Comments