3

I want to send json data in url as below .

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

How can I do this?

6 Answers 6

4

URL encode your details parameter:

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

String url = "editTest.jsp?details=" + URLEncoder.encode(otherParameter + jsonString, "UTF-8");
Sign up to request clarification or add additional context in comments.

4 Comments

Does this make sense? It encodes it to pretty strange looking url params: %7B%22aNumber%22%3A2%7D.
@AlexMoore-Niemi Have a look at this URL encoding reference: w3schools.com/tags/ref_urlencode.ASP
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!
This should not be the accepted answer. {"test":true,"name":"foo"} needs to be converted to test=true&name=foo
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.

6 Comments

The issue is the converted string contains ':' which is not works in url .
@SanjayaLiyanage you never said it in your question...!
@SanjayaLiyanage yep I know, but that is not your problem right?
ok Nishad I'm sorry If the question was not up to the point .Why I am unable to send the json data from the url is because it contains : .
Ok, sounds good. Why don't you use request object to pass parameters? Which framework are you using?
|
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("");
    }

Comments

0

Json2 can help. JSON.stringify(obj)

Comments

0

We can use the help of Gson

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

NB: jar file needed for Gson

1 Comment

This doesn't urlencode the data though.
0

I would like to add my solution:

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;


private static String createURIString(String str) {
    try {
        URI uri = new URI(str);
        return uri.toASCIIString();
    } catch (URISyntaxException x) {
        throw new IllegalArgumentException(x.getMessage(), x);
    }
}

private static String convertJSONBodyToURL(String input){
    // input = "{ \"name\": \"Test\", \"java\": true}";

    ArrayList<String> arr = new ArrayList<String>();
    
    JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
    for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue().toString();
            // remove "', new URI would fail
            value = value.replace("\"", "").replace("'", "");
        
        // value sanity checks
        String valueURI = FixAPI.createURIString(value);
        
        // fail in case of problems
        if(valueURI == null){
            // err
            return null;
        }

        // if safe, add to array            
        arr.add(key + "=" + value);
    }
    
    // join array to String
    String joinedURLString = String.join("&", arr);
    
    return joinedURLString;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.