我想以以下格式在URL中发送JSON数据。
我该如何做到这一点?
editTest.jsp?details=374889331-{"aNumber":2}
我该如何做到这一点?
editTest.jsp?details=374889331-{"aNumber":2}
将您的详细信息参数进行URL编码:
String otherParameter = "374889331-";
String jsonString = "{\"aNumber\":2}";
String url = "editTest.jsp?details=" + URLEncoder.encode(otherParameter + jsonString, "UTF-8");
您需要将JSON对象
转换为字符串。
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
jsonText
作为参数传递。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("");
}
Gson
的帮助。String result =new Gson().toJson("your data");
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;
}
%7B%22aNumber%22%3A2%7D
。 - Alex Moore-Niemi