Search code examples
javajsonspringweb-services

How to pass a JSON array as a parameter in URL


I have an requirement to pass a some values from mobile to server in a web service call and so I am planning to pass all the values in JSON format like the below

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

The following is my service call

@RequestMapping("/saveName")
@ResponseBody
public String saveName(String acc)
{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();
}

I am trying to call the above service by this way

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

But the output is like this

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

Can any body please tell me why I am not getting all the values please?


Solution

  • I would suggest passing the JSON data in the body as a POST request. But if you still want to pass this as a parameter in the URL, you will have to encode your URL like below for example:

    Example JSON:

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

    Example encoded URL:

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

    For more information on URL encoding, refer to percent-encoding.