如何将url中的json数据作为java中的请求参数发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26541801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:45:09  来源:igfitidea点击:

How to send json data in url as request parameters in java

javajsonhttp-request-parameters

提问by Sanjaya Liyanage

I want to send json data in url as below .

我想在 url 中发送 json 数据,如下所示。

editTest.jsp?details=374889331-{"aNumber":2}

How can I do this?

我怎样才能做到这一点?

采纳答案by eee

URL encode your details parameter:

URL 编码您的详细信息参数:

String otherParameter = "374889331-";    
String jsonString = "{\"aNumber\":2}";

String url = "editTest.jsp?details=" + URLEncoder.encode(otherParameter + jsonString, "UTF-8");

回答by Paris Tao

Json2can help. JSON.stringify(obj)

Json2可以提供帮助。JSON.stringify(obj)

回答by Nishad K Ahamed

you need to convert the JSON objectto string

您需要将转换JSON object为字符串

      JSONObject obj = new JSONObject();

      obj.put("name","foo");

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);

      String jsonText = out.toString();//JSON object is converted to string

Now, you can pass this jsonTextas parameter.

现在,您可以将其jsonText作为参数传递。

回答by Anptk

We can use the help of Gson

我们可以借助 Gson

String result =new Gson().toJson("your data");

NB: jar file needed for Gson

注意:Gson 需要 jar 文件

回答by limo_756

We can convert the Object to JSON Object using GSON, then parse the JSON object and convert it to query param string. The Object should only contain primitive objects like int, float, string, enum, etc. Otherwise, you need to add extra logic to handle those cases.

我们可以使用 GSON 将 Object 转换为 JSON Object,然后解析 JSON 对象并将其转换为查询参数字符串。Object 应该只包含原始对象,如 int、float、string、enum 等。否则,您需要添加额外的逻辑来处理这些情况。

public String getQueryParamsFromObject(String baseUrl, Object obj) {
        JsonElement json = new Gson().toJsonTree(obj);
        // Assumption is that all the parameters will be json primitives and there will
        // be no complex objects.
        return baseUrl + json.getAsJsonObject().entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue().getAsString())
                .reduce((e1, e2) -> e1 + "&" + e2)
                .map(res -> "?" + res).orElse("");
    }