Thursday, March 1, 2012

Converting to JSON Message to Map.

package com.varra;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.mt.classification.InterfaceAudience;
import com.mt.classification.InterfaceStability;


/**
 * TODO Description go here.
 *
 * @author Rajakrishna V. Reddy
 * @version 1.0
 *
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class JSONExample
{
   
    /** The logger to log the debugging messages as application runs. */
    private static final Logger logger = Logger.getLogger(JSONExample.class);
   
    public static void handleJSONObject(JSONObject jsonObject, Map<String, String> inputMap)
    {
        final Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext())
        {
            Object value = null;
            try
            {
                final String key = (String) iterator.next();
                value = jsonObject.get(key);
                if (value instanceof JSONObject)
                {
                    handleJSONObject((JSONObject) value, inputMap);
                }
                inputMap.put(key, value.toString());
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }
   
    /**
     * @param args
     * @throws JSONException
     */
    public static void main(String[] args) throws JSONException
    {
        final String input = "{\"bycustomer\":\"7,5,6\",\"byslastatus\":{\"breached\":\"<=1000\",\"safe\":\">=90\",\"abouttobreach\":\"<=100\"},\"bygroup\":\"37,35\",\"bysearch\":\"test\",\"bytype\":\"portal or media\",\"paused\":\"1\",\"pagelimit\":50,\"startlimit\":1,\"byticketstatusscope\":{\"assigned\":\"2,10\",\"accepted\":\"3\",\"workinprogress\":\"4\",\"pendingwithuser\":\"13\",\"pendingwithvendor\":\"12\"}}";
        final JSONObject jsonObject = new JSONObject(input);
        final Map<String, String> inputMap = new LinkedHashMap<String, String>();
        handleJSONObject(jsonObject, inputMap);
        System.out.println("values: "+inputMap);
       
        //System.out.println("jsonObject: "+jsonObject.getString("byslastatus"));
    }
}

No comments:

Post a Comment