【发布时间】:2015-05-06 05:37:53
【问题描述】:
我想使用 java 将 "id=1&location=india" 查询字符串转换为 {"id":"1","location":"india"} json 格式。
我使用的是 spring 版本 4.0.3。
【问题讨论】:
-
告诉我们你做了什么,你在哪里卡住了
标签: java json jersey jettison flexjson
我想使用 java 将 "id=1&location=india" 查询字符串转换为 {"id":"1","location":"india"} json 格式。
我使用的是 spring 版本 4.0.3。
【问题讨论】:
标签: java json jersey jettison flexjson
嗯,这不是直接的方法,但这是我想到的第一个方法。 使用 HttpUtils 将 queryString 转换为 Hashtable,然后将其编组为 JSON。
https://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/http/HttpUtils.html
更新: HttpUtils 生成 Hashtable。
【讨论】:
我觉得你可以这样写一个转换器
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;
}
}
它可以为你完成这项工作
【讨论】:
试试这个..
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());
}
【讨论】: