spydon spydon - 1 year ago 98
Java Question

Library to convert JSON to urlencoded

We are doing some integration towards a quite inconsistent (Zurmo-)REST API. The API only accepts urlencoded strings as its payload in the http posts, but it answers with JSON.
So as the documentation was very unclear on this we naturally thought we could post JSON to it, but this was not the case.

So now we have all our code generating JSON when we need to send it as x-www-form-urlencoded, is there any java library that can do a conversion from JSON to an urlencoded string?

We are currently using the org.json lib, but we can change it if there would be a need for it.


This JSON string:

{"data":{"description":"test","occurredOnDateTime":"2013-10-24 01:44:50"}}

Should be converted into this:


Java code:

We translated rasmushaglunds javascript code to java and wrapped it, here is the result if anybody else stumbles upon this problem.

public static String jsonToURLEncoding(JSONObject json) {
String output = "";
String[] keys = JSONObject.getNames(json);
for (String currKey : keys)
output += jsonToURLEncodingAux(json.get(currKey), currKey);

return output.substring(0, output.length()-1);

private static String jsonToURLEncodingAux(Object json, String prefix) {
String output = "";
if (json instanceof JSONObject) {
JSONObject obj = (JSONObject)json;
String[] keys = JSONObject.getNames(obj);
for (String currKey : keys) {
String subPrefix = prefix + "[" + currKey + "]";
output += jsonToURLEncodingAux(obj.get(currKey), subPrefix);
} else if (json instanceof JSONArray) {
JSONArray jsonArr = (JSONArray) json;
int arrLen = jsonArr.length();

for (int i = 0; i < arrLen; i++) {
String subPrefix = prefix + "[" + i + "]";
Object child = jsonArr.get(i);
output += jsonToURLEncodingAux(child, subPrefix);
} else {
output = prefix + "=" + json.toString() + "&";

return output;

Answer Source

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);
      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


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