2

I want to convert "id=1&location=india" querystring to {"id":"1","location":"india"} json format using java.

I am using spring version 4.0.3.

mort
  • 12,988
  • 14
  • 52
  • 97
Devloper
  • 120
  • 3
  • 14

3 Answers3

0

Well this is not a direct way, but this is the first though came to my mind. Convert the queryString to Hashtable using HttpUtils , then marshall it into JSON.

https://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/http/HttpUtils.html

Update: HttpUtils produces Hashtable.

ppuskar
  • 773
  • 6
  • 9
0

I think you can write a converter like this

public class ConvertToJson {
    public static void main(String[] args) {
        String a = "id=1&location=india";
        System.out.println(convert(a));
    }

    private static String convert(String a) {
        String res = "{\"";

        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == '=') {
                res += "\"" + ":" + "\"";
            } else if (a.charAt(i) == '&') {
                res += "\"" + "," + "\"";
            } else {
                res += a.charAt(i);
            }
        }
        res += "\"" + "}";
        return res;
    }
}

it can do the job for you

Ge Jun
  • 115
  • 1
  • 6
0

try this..

 try
    {
        String query="id=1&location=india";
        String queryArray[]=query.split("&");
        String id[]=queryArray[0].split("=");
        String location[]=queryArray[1].split("=");

        JSONObject jsonObject=new JSONObject();
        jsonObject.put(id[0],id[1]);
        jsonObject.put(location[0],location[1]);

        Log.i("Stackoverflow",jsonObject.toString());
    }
    catch (JSONException e)
    {
        e.printStackTrace();
        Log.i("Stackoverflow",e.getMessage());
    }
Angad Tiwari
  • 1,738
  • 1
  • 12
  • 23