3

I want to send json data in url as below .

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

How can I do this?

Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50

5 Answers5

5

URL encode your details parameter:

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

String url = "editTest.jsp?details=" + URLEncoder.encode(otherParameter + jsonString, "UTF-8");
eee
  • 3,241
  • 1
  • 17
  • 34
  • Does this make sense? It encodes it to pretty strange looking url params: `%7B%22aNumber%22%3A2%7D`. – Alex Moore-Niemi Apr 09 '21 at 16:20
  • @AlexMoore-Niemi Have a look at this URL encoding reference: https://www.w3schools.com/tags/ref_urlencode.ASP – eee Apr 09 '21 at 20:29
  • The encoding itself is fine, but it's encoding the brackets and such as well. That doesn't seem exactly equivalent to sending "foo=bar" and I don't think all servers will interpret it to be the same. I guess that's what the poster is asking for though! – Alex Moore-Niemi Apr 11 '21 at 15:48
2

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.

Nishad K Ahamed
  • 1,374
  • 15
  • 25
1

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("");
    }
limo_756
  • 177
  • 3
  • 10
0

Json2 can help. JSON.stringify(obj)

Paris Tao
  • 335
  • 1
  • 3
  • 11
0

We can use the help of Gson

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

NB: jar file needed for Gson

Anptk
  • 1,125
  • 2
  • 17
  • 28