JSON to Map - Java JSON

Java examples for JSON:JSON String

Description

JSON to Map

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   www. j  a  v a 2 s.c  om
    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