Library to convert JSON to urlencoded

左心房为你撑大大i 提交于 2019-12-03 06:59:24

As noted below, it's not a Java library but you should be able to translate it :)

Here's how you could do it in javascript:

var jsonArrayToUrl = function (obj, prefix) {
  var urlString = "";
  for (var key in obj) {
    if (obj[key] !== null && typeof obj[key] == "object") {
      prefix += "[" + key + "]";
      urlString += jsonArrayToUrl(obj[key], prefix);
    }else{
      urlString += prefix + "[" + key + "]=" + obj[key] + "&";
    }
  }
  return encodeURIComponent(urlString);
};

Then call it with

jsonArrayToUrl(test["data"], "data");

By the example string you gave above it returns

"data%5Bdescription%5D%3Dtest%26data%5BoccurredOnDateTime%5D%3D2013-10-24%2001%3A44%3A50%26"

It should work recursively on nested arrays. You might also consider writing a wrapper for the function so that you only need one argument.

public static String objectToUrlEncodedString(Object object, Gson gson) {
    return jsonToUrlEncodedString((JsonObject) new JsonParser().parse(gson.toJson(object)));
}

private static String jsonToUrlEncodedString(JsonObject jsonObject) {
    return jsonToUrlEncodedString(jsonObject, "");
}

private static String jsonToUrlEncodedString(JsonObject jsonObject, String prefix) {
    String urlString = "";
    for (Map.Entry<String, JsonElement> item : jsonObject.entrySet()) {
        if (item.getValue() != null && item.getValue().isJsonObject()) {
            urlString += jsonToUrlEncodedString(
                    item.getValue().getAsJsonObject(),
                    prefix.isEmpty() ? item.getKey() : prefix + "[" + item.getKey() + "]"
            );
        } else {
            urlString += prefix.isEmpty() ?
                    item.getKey() + "=" + item.getValue().getAsString() + "&" :
                    prefix + "[" + item.getKey() + "]=" + item.getValue().getAsString() + "&";
        }
    }
    return urlString;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!