JSONFormatter (JSONObject into Map, JSONArray into List, intermediate recursive call class)

Tips:
JSONFormatter, defines a toMap method (converts JSONObject to Map) and a toList method (converts JSONArray to List). Through recursive calls between each other, the final conversion of the final SONObject and JSONArray is realized

Code:
package com.cisco.cmse.du.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


public final class JSONFormatter {

    /**
     * JSONObject to map
     * @param object json object
     * @return the converted Map
     */
    public static Map<String, Object> toMap(JSONObject object){
        Map<String, Object> map = new HashMap<String, Object>();

        for (Iterator<?> it = object.keys(); it.hasNext();) {
        	String key = (String)it.next();
            Object value;
			try {
				value = object.get(key);
				if(value instanceof JSONArray) {
	                value = toList((JSONArray) value);
	            }

	            else if(value instanceof JSONObject) {
	                value = toMap((JSONObject) value);
	            }
	            map.put(key, value);
			} catch (JSONException e) {
				e.printStackTrace ();
			}
            
        }

        return map;
    }

    /**
     * Convert JSONArray to List
     * @param array json array
     * @return the converted List
     */
    public static List<Object> toList(JSONArray array){
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value;
			try {
				value = array.get(i);
				if(value instanceof JSONArray) {
	                value = toList((JSONArray) value);
	            }

	            else if(value instanceof JSONObject) {
	                value = toMap((JSONObject) value);
	            }
	            list.add(value);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
            
        }
        return list;
    }
}





Code:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326035080&siteId=291194637