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

前端 未结 5 1222
余生分开走
余生分开走 2020-12-10 21:54

I want to send json data in url as below .

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

How can I do this?

相关标签:
5条回答
  • 2020-12-10 22:28

    you need to convert the JSON object to string

          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 jsonText as parameter.

    0 讨论(0)
  • 2020-12-10 22:28

    Json2 can help. JSON.stringify(obj)

    0 讨论(0)
  • 2020-12-10 22:37

    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.

    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("");
        }
    
    0 讨论(0)
  • 2020-12-10 22:45

    URL encode your details parameter:

    String otherParameter = "374889331-";    
    String jsonString = "{\"aNumber\":2}";
    
    String url = "editTest.jsp?details=" + URLEncoder.encode(otherParameter + jsonString, "UTF-8");
    
    0 讨论(0)
  • 2020-12-10 22:46

    We can use the help of Gson

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

    NB: jar file needed for Gson

    0 讨论(0)
提交回复
热议问题