Library to convert JSON to urlencoded

后端 未结 2 828
忘了有多久
忘了有多久 2021-02-09 00:31

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.

2条回答
  •  [愿得一人]
    2021-02-09 01:35

    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.

提交回复
热议问题