Object to JSON - Java JSON

Java examples for JSON:JSON String

Description

Object to JSON

Demo Code


import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public class Main{
    /*from ww  w . j a  v  a 2s .co  m*/
    public static JSONObject toJSON(Object bean) {

        return new JSONObject(toMap(bean));

    }
    
    public static Map<String, Object> toMap(Object javaBean) {

        Map<String, Object> result = new HashMap<String, Object>();
        Method[] methods = javaBean.getClass().getDeclaredMethods();

        for (Method method : methods) {

            try {

                if (method.getName().startsWith("get")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0)
                            + field.substring(1);

                    Object value = method.invoke(javaBean);
                    result.put(field, value);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return result;

    }
    
    public static Map<String, Object> toMap(String jsonString)
            throws JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);

        return toMap(jsonObject);

    }
    public static Map<String, Object> toMap(JSONObject jsonObject) {
        Map<String, Object> result = new HashMap<String, Object>();
        Iterator<String> iterator = jsonObject.keys();
        String key = null;
        Object value = null;

        while (iterator.hasNext()) {

            key = iterator.next();
            value = jsonObject.get(key);
            if (value != null) {
                result.put(key, value);
            }
        }
        return result;
    }
}

Related Tutorials