48

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?

rocking
  • 4,729
  • 9
  • 30
  • 45

10 Answers10

56

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

for ex json is :->{"name":"ABC","id":"1"}

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

for more information on URL encoding refer below

https://en.wikipedia.org/wiki/Percent-encoding

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
dReAmEr
  • 6,986
  • 7
  • 36
  • 63
  • 1
    Can you please tell me how to pass using POST – rocking Dec 20 '14 at 09:39
  • 1
    what you are using for your front end,i mean for making request to spring service? is it AJAX or JAVA or what?? – dReAmEr Dec 20 '14 at 09:40
  • This is a webservice call.Android guys will have to send me data and I have to keep in the DB. – rocking Dec 20 '14 at 09:43
  • which language they are using to make this web service call? – dReAmEr Dec 20 '14 at 09:46
  • For POST method support, you will have to change your spring service like @RequestMapping(value ="/saveName",method = RequestMethod.POST) @ResponseBody public String saveName(@RequestBody 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(); } and ask your Android guyz to make the POST request,that;s it. – dReAmEr Dec 20 '14 at 09:58
  • In webservice call,we are always passing the datas in the url so its always get method – rocking Dec 20 '14 at 10:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67371/discussion-between-re350-and-rocking). – dReAmEr Dec 20 '14 at 10:01
  • In this question http://stackoverflow.com/questions/27578967/how-to-decode-jsonobject ,under the accepted answer I have asked the answerer how to deal with the other data format but the answerer did not respond.Can you answer that please/ – rocking Dec 22 '14 at 05:46
  • the question is already answered and you accepted it,if it does't answer ,you will have to ask a new question. – dReAmEr Dec 22 '14 at 06:06
  • yes it has an answer and I have accepted also.But I had new requirement now and asked the answwer but I didnt get any response.Can you answer there also and I will upvote your answer for sure – rocking Dec 22 '14 at 09:05
  • What if I don't want de `data` parameters, I want straight the other ones? Is there a way to do this directly instead of mapping each key in the JSON and encoding the values? – Rodrigo Ruiz Nov 24 '17 at 00:31
50

I know this could be a later post, but, for new visitors I will share my solution, as the OP was asking for a way to pass a JSON object via GET (not POST as suggested in other answers).

  1. Take the JSON object and convert it to string (JSON.stringify)
  2. Take the string and encode it in Base64 (you can find some useful info on this here
  3. Append it to the URL and make the GET call
  4. Reverse the process. decode and parse it into an object

I have used this in some cases where I only can do GET calls and it works. Also, this solution is practically cross language.

gvelasquez85
  • 511
  • 4
  • 3
  • 1
    This should be the solution. In some cases, the APIs, are limited to GET and this idea just saved me! – isklikas Jun 21 '18 at 12:36
  • 12
    You don't need base64. You should be fine with `encodeURIComponent()`. – lenooh Oct 08 '18 at 15:46
  • 1
    @lenooh yes, it will work, but you need it, because encodeURIComponent() will add characters to the URL (maybe 2 or 3 per non alphabetical character) and probably you will fill the 2048 character URL limit very quickly. Base64 will try to encode in binary form, so, It will get lesser characters. – gvelasquez85 Oct 30 '20 at 15:39
  • 3
    Base64 is not safe for a URL, as discussed in the link given in answer. Alternatives are a) [Use different 64 characters: base64url](https://en.wikipedia.org/wiki/Base64#URL_applications) OR b) [urlencode the base64 data](https://stackoverflow.com/a/12591941/199364). – ToolmakerSteve Dec 12 '20 at 01:05
6

I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand & is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R. So the acc parameter ends when it reaches the ampersand character.

That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.

Adriano
  • 3,788
  • 5
  • 32
  • 53
4

& is a keyword for the next parameter like this ur?param1=1&param2=2

so effectively you send a second param named R". You should urlencode your string. Isn't POST an option?

Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111
wgitscht
  • 2,676
  • 2
  • 21
  • 25
3

You can pass your json Input as a POST request along with authorization header in this way

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

pintu
  • 331
  • 4
  • 7
1

I encountered the same need and make a universal solution (node+browser) that works with the Next.js framework, for instance.

It even works with circular dependencies (thanks to json-stringify-safe).

Although, I also built a serializer on top of it to remove unnecessary data (because it's not recommended to use a url longer than 2k chars, see What is the maximum length of a URL in different browsers?)

import StringifySafe from 'json-stringify-safe';

export const encodeQueryParameter = (data: object): string => {
  return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};

export const decodeQueryParameter = (query: string): object => {
  return JSON.parse(decodeURIComponent(query));
};

And the unit tests (jest):

import { decodeQueryParameter, encodeQueryParameter } from './url';

export const data = {
  'organisation': {
    'logo': {
      'id': 'ck2xjm2oj9lr60b32c6l465vx',
      'linkUrl': null,
      'linkTarget': '_blank',
      'classes': null,
      'style': null,
      'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
      'mimeType': 'image/png',
      '__typename': 'Asset',
    },
    'theme': {
      'primaryColor': '#1134e6',
      'primaryAltColor': '#203a51',
      'secondaryColor': 'white',
      'font': 'neuzeit-grotesk',
      '__typename': 'Theme',
      'primaryColorG1': '#ffffff',
    },
  },
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';

describe(`utils/url.ts`, () => {
  describe(`encodeQueryParameter`, () => {
    test(`should encode a JS object into a url-compatible string`, async () => {
      expect(encodeQueryParameter(data)).toEqual(encodedData);
    });
  });

  describe(`decodeQueryParameter`, () => {
    test(`should decode a url-compatible string into a JS object`, async () => {
      expect(decodeQueryParameter(encodedData)).toEqual(data);
    });
  });

  describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
    test(`should encode and decode multiple times without altering data`, async () => {
      const _decodedData: object = decodeQueryParameter(encodedData);
      expect(_decodedData).toEqual(data);

      const _encodedData: string = encodeQueryParameter(_decodedData);
      expect(_encodedData).toEqual(encodedData);

      const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
      expect(_decodedDataAgain).toEqual(data);
    });
  });
});
Vadorequest
  • 16,593
  • 24
  • 118
  • 215
0

As @RE350 suggested passing the JSON data in the body in the post would be ideal. However, you could still send the json object as a parameter in a GET request, decode the json string in the server-side logic and use it as an object.

For example, if you are on php you could do this (use the appropriate json decode in other languages):

Server request:

http://<php script>?param1={"nameservice":[{"id":89},{"id":3}]}

In the server:

$obj = json_decode($_GET['param1'], true);
$obj["nameservice"][0]["id"]

out put:

89
picmate 涅
  • 3,951
  • 5
  • 43
  • 52
0

Send Json data string to a web address and get a result with method post

in C#

public string SendJsonToUrl(string Url, string StrJsonData)
{
    if (Url == "" || StrJsonData == "") return "";
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = StrJsonData.Length;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(StrJsonData);
            streamWriter.Close();
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    catch (Exception exp)
    {
        throw new Exception("SendJsonToUrl", exp);
    }
}

in PHP

<?php

$input = file_get_contents('php://input');
$json = json_decode($input ,true);

?>
Amirali Eshghi
  • 963
  • 1
  • 14
  • 21
0

You may send array in the URL like this:

send each fileld FIELDS[POST_MESSAGE]

https://crm654.com/task.comment.add.json?taskId=625&FIELDS[POST_MESSAGE]='bingo!'

-1
let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');
plutomusang
  • 59
  • 1
  • 6