Library to convert JSON to urlencoded

后端 未结 2 827
忘了有多久
忘了有多久 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:16

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

提交回复
热议问题