1

I'm sending from my client side an ajax request to my server.

this is the data structure that i'm passing:

data = {"key1" : "value1" , "key2" : {"subkey1": "subvalue1" ,"subkey2" : "subvalue2"}};

on the server side i'm doing the following:

   private Map<String, Object> parseItemData(HttpServletRequest request) {

    Enumeration<String> parameterNames = request.getParameterNames();

    while (parameterNames.hasMoreElements()) {

        String paramName = parameterNames.nextElement();

        String[] paramValues = request.getParameterValues(paramName);

        if(paramName.equals("itemSpecifics"))
        {
            System.out.println(paramName);

            for (int i =0 ; i<paramValues.length; i++)
            {
                System.out.println(paramName +": "+paramValues[i] );
            }
        }
    }
    return item;
}

this is the output that i'm getting:

itemSpecifics: [object Object]

is there any way to do it?


Solution :

in case of nested key value pair, i had to manual use JSON.stringify() for the nested key value in order to send it as JSON.

USer22999299
  • 5,284
  • 9
  • 46
  • 78

2 Answers2

3

This may help you.

Use getParameterMap() method to get all key value pairs.

Map<String, String[]> requestParams = request.getParameterMap();

Below code to get JSONObject:

JSONObject jsonObject=null;
        Map<String,String> out = new HashMap<String, String>();
        Map<String,String[]> map = request.getParameterMap();

        for (Map.Entry<String,String[]> mapEntry : map.entrySet()) {

          String value[] = mapEntry.getValue();
          Object object = value.length == 1 ? value[0] : value;
          try {
              jsonObject = new JSONObject((String)object);
              parse(jsonObject,out);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        }
        response.getWriter().print(out);

To parse json use parse function : I have taken help from How can I iterate JSONObject to get individual items

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
        Iterator<String> keys = json.keys();
        while(keys.hasNext()){
            String key = keys.next();
            String val = null;
            try{
                 JSONObject value = json.getJSONObject(key);
                 parse(value,out);
            }catch(Exception e){
                val = json.getString(key);
            }

            if(val != null){
                out.put(key,val);
            }
        }
        return out;
    }
Community
  • 1
  • 1
Vishvesh Phadnis
  • 2,448
  • 5
  • 19
  • 35
  • was trying to use it as Map requestParams = request.getParameterMap(); and cast it while having the right key for that, but it cannot cast from string to map 'Ljava.lang.String; cannot be cast to java.util.Map' – USer22999299 Nov 28 '14 at 07:32
  • for some reason the get action returning string object insted of Object – USer22999299 Nov 28 '14 at 07:34
  • getParameterMap() returns Map only. iterate through string to get other values using json or jackson library – Vishvesh Phadnis Nov 28 '14 at 07:37
  • Map requestParams = request.getParameterMap(); JSONObject jsonObj = (JSONObject)rquestParams.get("itemSpecifics"); By doing that i'm getting the compilation error of Cannot cast from String[] to JSONObject, as the above suggestion.. – USer22999299 Nov 28 '14 at 07:43
  • I updated code.Please check. or still you facing issue? – Vishvesh Phadnis Nov 28 '14 at 08:44
  • While doing that and printing the 'jsonObject' , i'm getting: {... , "itemSpecifics":"[object Object]" , ...} Seems like the data is sent the wrong way? – USer22999299 Nov 28 '14 at 09:30
  • Please post actual json. – Vishvesh Phadnis Nov 28 '14 at 09:50
  • Updated Answer and added parse function – Vishvesh Phadnis Nov 28 '14 at 10:00
  • Found the problem , while sending with ajax json with nested key value i have to use JSON.stringify for the nested list other wise the post method will send it as [object Object] and not as json string. Any way your code is working for me :) thanks! – USer22999299 Nov 28 '14 at 10:01
1

You could try this. As sysout prints [Object,Object] that means there are two String Objects.

Onw of possible way to declare a String Array like this

String[] keyValPair = new String[]{"\"key1\" : \"value1\"","key2:{}"} This is just a guess how container is parsing this Json like data. May be it converts it in two different String Objects put it as a String Array.

    String[] paramValues = request.getParameterValues(paramName);

    if(paramName.equals("itemSpecifics"))
    {
     System.out.println(paramName);

     String[] paramArr = (String[]) paramValues[0];
     String firstKeyVal = paramArr [0];//Contains "key1" : "value1" as String
     String secondKeyVal = paramArr [1];//Contains "key2" : {"subkey1": "subvalue1" ,"subkey2" : "subvalue2"} as String

     String value1= firstKeyVal.split(":")[1];
     String[] subValues = secondKeyVal.substring(secondKeyVal.indexOf("{")+1,secondKeyVal.indexOf("}")).split(",");
    String subVal1 = subValues[0].split(":")[1];
    String subVal2 = subValues[1].split(":")[1];

     System.out.println(paramName+" value1"+value1+" subVal1 "+subVal1+" subVal2 "+subVal2);

     }

The Best way is to pass all parameters as JSON.

Anurag Anand
  • 500
  • 1
  • 7
  • 13
  • This is what i'm getting: Cannot cast from String to JSONObject. any idea? – USer22999299 Nov 28 '14 at 07:21
  • @USer22999299 I do not think you are getting a String, you are getting an array of Objects because `sysout` prints `[object Object]`, it does not print String value.Calling `paramValues[i].toString()` will give the same output. Have you tried this approach. – Anurag Anand Nov 28 '14 at 07:32
  • while applying the code above, i'm getting the compilation error of Cannot cast from String to JSONObject. paramValues is a String[] – USer22999299 Nov 28 '14 at 07:36
  • @USer22999299 I have updated my answer, by assuming how container will parse this string data. – Anurag Anand Nov 28 '14 at 08:22