Passing JSON Array as URL Parameter: Encoding and Best Practices

Nov 21, 2025 · Programming · 9 views · 7.8

Keywords: URL Encoding | JSON Array | Spring Framework | GET Request | Data Transmission

Abstract: This article explores the technical implementation of passing JSON array parameters in URLs, focusing on the necessity of URL encoding and its application in the Spring framework. By comparing the suitability of GET and POST requests, it explains in detail how to properly encode JSON data to avoid truncation during transmission. The article provides concrete code examples demonstrating URL encoding implementation and offers cross-language compatible alternatives, helping developers choose the optimal data transmission method based on actual requirements.

Problem Background and Phenomenon Analysis

In web service calls between mobile clients and servers, developers often need to pass structured data through URL parameters. The user attempted to pass a JSON array containing multiple objects as a URL parameter, with the specific data structure as follows:

{
    "nameservice": [
        {
            "id": 7413,
            "name": "ask"
        },
        {
            "id": 7414,
            "name": "josn"
        },
        {
            "id": 7415,
            "name": "john"
        },
        {
            "id": 7418,
            "name": "R&R"
        }
    ]
}

The corresponding Spring MVC server-side code is:

@RequestMapping("/saveName")
@ResponseBody
public String saveName(String acc) {
    JSONObject jsonObject = new JSONObject();
    try {
        System.out.println(acc);
        jsonObject.accumulate("result", "saved ");
    } catch(Exception e) {
        e.printStackTrace();
        jsonObject.accumulate("result", "Error Occured ");
    }
    return jsonObject.toString();
}

When calling the service via URL:

localhost:8080/service/saveName?acc={ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "R&R" } ] }

The actual output showed data truncation:

{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "R

This phenomenon occurs because special characters in the URL (such as spaces, quotes, and curly braces) are not encoded, causing premature termination during server-side parsing.

URL Encoding Solution

URL encoding (percent-encoding) is the core method to solve this problem. It converts special characters into a % followed by two hexadecimal digits, ensuring data integrity during transmission.

Taking a simple JSON object as an example:

{"name":"ABC","id":"1"}

After URL encoding:

%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

Complete URL example:

testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

In Java, automatic encoding can be achieved using java.net.URLEncoder:

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

String jsonData = "{\"name\":\"ABC\",\"id\":\"1\"}";
String encodedData = URLEncoder.encode(jsonData, StandardCharsets.UTF_8);
String url = "http://testurl:80/service?data=" + encodedData;

The server-side should be modified for automatic decoding:

@RequestMapping("/saveName")
@ResponseBody
public String saveName(@RequestParam("acc") String acc) {
    JSONObject jsonObject = new JSONObject();
    try {
        // Automatically decode URL parameter
        String decodedData = java.net.URLDecoder.decode(acc, StandardCharsets.UTF_8);
        System.out.println(decodedData);
        jsonObject.accumulate("result", "saved ");
    } catch(Exception e) {
        e.printStackTrace();
        jsonObject.accumulate("result", "Error Occured ");
    }
    return jsonObject.toString();
}

Alternative Solutions and Cross-Language Compatibility

For scenarios where GET requests must be used, Base64 encoding provides another cross-language compatible solution:

  1. Convert JSON object to string: JSON.stringify(jsonObject)
  2. Encode the string using Base64
  3. Append the encoded result to the URL
  4. Perform Base64 decoding on the server side and parse into an object

JavaScript encoding example:

const jsonData = {nameservice: [{id: 7413, name: "ask"}]};
const jsonString = JSON.stringify(jsonData);
const base64Data = btoa(jsonString); // Base64 encoding
const url = `localhost:8080/service/saveName?acc=${base64Data}`;

Java server-side decoding example:

import java.util.Base64;

@RequestMapping("/saveName")
@ResponseBody
public String saveName(@RequestParam("acc") String acc) {
    JSONObject jsonObject = new JSONObject();
    try {
        byte[] decodedBytes = Base64.getDecoder().decode(acc);
        String decodedJson = new String(decodedBytes, StandardCharsets.UTF_8);
        JSONObject data = new JSONObject(decodedJson);
        System.out.println(data.toString());
        jsonObject.accumulate("result", "saved ");
    } catch(Exception e) {
        e.printStackTrace();
        jsonObject.accumulate("result", "Error Occured ");
    }
    return jsonObject.toString();
}

Request Method Selection and Best Practices

Although the above methods enable JSON transmission in GET requests, from RESTful design principles, POST requests are more suitable for complex data:

@RequestMapping(value = "/saveName", method = RequestMethod.POST)
@ResponseBody
public String saveName(@RequestBody Map<String, Object> requestData) {
    JSONObject jsonObject = new JSONObject();
    try {
        System.out.println(requestData);
        jsonObject.accumulate("result", "saved ");
    } catch(Exception e) {
        e.printStackTrace();
        jsonObject.accumulate("result", "Error Occured ");
    }
    return jsonObject.toString();
}

Client call example:

fetch('localhost:8080/service/saveName', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        "nameservice": [
            {"id": 7413, "name": "ask"},
            {"id": 7414, "name": "josn"}
        ]
    })
})

Considering all factors, it is recommended to: use URL-encoded GET requests for small data volumes; prioritize POST requests for complex or large data; consider Base64 solutions when cross-language compatibility is required.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.