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?
This question is related to
java
json
spring
web-services
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).
I have used this in some cases where I only can do GET calls and it works. Also, this solution is practically cross language.
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
& is a keyword for the next parameter like this ur?param1=1¶m2=2
so effectively you send a second param named R". You should urlencode
your string. Isn't POST an option?
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);
?>
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);
});
});
});
let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');
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.
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
Source: Stackoverflow.com