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.
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.
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.
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
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());
}