1

我想使用 java 将"id=1&location=india"查询字符串转换为{"id":"1","location":"india"}json 格式。

我正在使用弹簧版本 4.0.3。

4

3 回答 3

0

好吧,这不是直接的方法,但这是我想到的第一个方法。使用 HttpUtils 将 queryString 转换为 Hashtable,然后将其编组为 JSON。

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

更新:HttpUtils 产生 Hashtable。

于 2015-05-06T05:42:08.353 回答
0

我想你可以写一个这样的转换器

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;
    }
}

它可以为您完成工作

于 2015-05-06T05:50:50.397 回答
0

尝试这个..

 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());
    }
于 2015-05-06T06:00:58.657 回答