I'm facing issues with ExtJS 4.1.3.
In my ExtJS controller, I call an ajax request like this :
Ext.Ajax.request(
{
url: '/my/url/method.do'
,timeout: 1800000
,jsonData: param
,success:function(response)
{
var jsonData = Ext.JSON.decode(response.responseText);
alert(jsonData);
// some code
}
,failure:function(response)
{
// some code
}
,scope:this
}
);
This is the method called in spring :
#RequestMapping(value = "/my/url/method.do")
public #ResponseBody String method(Locale userLocale, #RequestBody Param[] param) {
return "string" + "<br/>" + "string";
}
It works well on Google Chrome and IE but not on Firefox. Indeed, I get the following error :
Ext.Error: You're trying to decode an invalid JSON String: string<br/>string
And I don't know why it doesn't work because if I execute the following code in the Firefox console, it works :
Ext.JSON.decode("string<br/>string")
So if anyone could help me, I would be grateful !
Thanks for your answers.
This website http://jsonlint.com/ indicates "string<br/>string" as a valid JSON string. But it is a "false" JSON validation cause it is not proper JSON format.
I solved my problem adding produce="application/json" in the #EequestMapping annotation of the controller. So now Ext.JSON.decode() works even with Firefox.
I could also send back an object serializable with the ajax request and then decode the response to get the data (with my string in it) because Spring automatically serialize object to JSON.
Related
Im trying to pass a string to an api method in flutter.
This is my api method format:
[HttpPut]
public async Task<ActionResult> PutInterests(string value)
{ .....}
This is my flutter request knowing that value is a string:
final response = await client.put(
"http://"+base+":8070/api/Connectors",
headers: {"content-type": "application/json"},
body:json.encode(value)
);
I am continuously getting internal server error (500).
Note that im sure the url is correct and there is no other put method in the controller. Also, the string received is either null or empty based on my code inside the api method.
Any help is appreciated.
I am using Chrome extension - Postman app to test my webservice. Below is the template of my webservice -
#POST
#Path("/usertransaction/get/amount")
#Produces("application/json")
#Consumes("application/json")
public List<ABCForm> getAmount(List<ABCForm> abclist, Date asOfDate) {
.
.
.
}
I have set header as application/json;charset=UTF-8 and request body as below -
[
{
"ccc":"1",
"qqq":"22",
"acac":"24",
"abc":"100"
}
],
"asOfDate":"05/05/2018"
I am aware that its not a valid JSON. But even if i resolve JSON issue, it still throws the same exception. I am looking for proper JSON through which request could be made and resolve this exception.Any help would be appreciated.
I recently upgraded my angular project from version 4.2 to version 6. Everything works great, except I noticed that angular is now removing functions from my json payload when making a post request(this may be happening for other http options also but haven't checked them). Is there a way to disable this or a work around besides json.stringify?
Here's the json payload that I'm trying to post:
{
name: "ghq_employeesTotal",
fieldMapping: ['item1'],
translation: Ć’unction(val){ return val.toLowerCase()}
}
Here's the payload that I see being sent in the network tab:
{
name: "ghq_employeesTotal",
fieldMapping: ['item1']
}
As you can see it's completely removing my translation property.
Here's my function sending the post request:
public publishConfig(config): Observable<any>{
return this.http.post<any>(this.serviceURL + 'publish', config);
}
Ć’unction(val){ return val.toLowerCase()} is not a valid JSON data type.
JSON only supports arrays, objects and primitive values.
Started testing my jQuery applications with IE9. Looks like I may be in for some trouble here.
I noticed that when I return JSON data back to the Javascript methods I always get this Prompt that says: "Do you want to open or save this file?" and provides me with 3 buttons: Open, Save and Cancel. Of course, my javascript is taking actions based on the values set in the JSON object but since IE9 doesn't pass it over to the script, I cannot execute the follow up action from there on.
Anyone else facing this issue? Here is a snapshot.
If anyone is using ASP.net MVC and trying to fix this issue - I used the following built in methods in the MVC framework. Simply update the content Type and encoding on the JsonResult.
public ActionResult Index(int id)
{
// Fetch some data
var someData = GetSomeData();
// Return and update content type and encoding
return Json(someData, "text/html", System.Text.Encoding.UTF8,
JsonRequestBehavior.AllowGet);
}
This fixed the issue for me!
(Answer originally posted for this question.)
If using MVC, one way of handling this is to implement a base controller in which you override (hide) the Json(object) method as follows:
public class ExtendedController : Controller
{
protected new JsonResult Json(object data)
{
if (!Request.AcceptTypes.Contains("application/json"))
return base.Json(data, "text/plain");
else
return base.Json(data);
}
}
Now, your controllers can all inherit ExtendedController and simply call return Json(model); ...
without modifying the response content type for those browsers which play nicely (not <=IE9 !)
without having to remember to use Json(data, "text/plain") in your various Ajax action methods
This works with json requests which would otherwise display the "Open or Save" message in IE8 & IE9 such as those made by jQuery File Upload
I also faced this problem yesterday with WebAPI which returned a list of URLs (of asynchronously uploaded files).
Just set content type to "text/html" instead of default "application/json; charset=UTF-8" of WebAPI services. I got response as a JSON string and then used $.parseJSON to convert it to JSON object.
public async Task<HttpResponseMessage> Upload()
{
// ...
var response = Request.CreateResponse(HttpStatusCode.OK, files);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
// result is an iframe's body content that received response.
$.each($.parseJSON(result.html()), function (i, item)
{
console.log(item.Url);
});
In my case when contentType in response header is "application/json; charset=UTF-8", the IE 9 shows that Prompt. But changed to "text/html" then the prompt does not show, although all otter browsers are fine with the "application/json; charset=UTF-8".
Actually, you were right #EricLaw. After setting the content type in the Json result, it worked.
I had to add the following lines:
result.ContentEncoding = System.Text.Encoding.UTF8;
result.ContentType = "application/json; charset=UTF-8
I got a REST WCF Service running in .net 4 and I've tested the web service it is working and accepting HttpRequest I make to it. But I ran into a problem trying to access the HttpRequest body within the web service. I've tried sending random sizes of data appended on the HttpRequest using both Fiddler and my WinForm app and I can't seem to find any objects in runtime where I can find my request body is located. My initial instinct was to look in the HttpContext.Current.Request.InputStream but the length of that property is 0, so I tried looking in IncomingWebRequestContext that object doesn't even have a method nor properties to get the body of the HttpRequest.
So my question is, is there actually a way to access the HttpRequest request body in WCF?
PS:
The data inside the request body is JSON strings and for response it would return the data inside response body as JSON string too.
Much simpler, this answer on WCF + REST: Where is the request data? works fine.
Also, if your request body is deserializable, you can just pass a class. Barring some typos, this should work:
public class Banana
{
public string Colour;
public int Size;
}
...
[WebInvoke(
Method = "POST",
UriTemplate = "bananas",
ResponseFormat=WebMessageFormat.Json,
RequestFormat=WebMessageFormat.Json)]
string CreateBanana(Banana banana);
...
public string CreateBanana(Banana banana)
{
return "It's a " + banana.Colour + " banana!";
}
Doing POST with data {"Colour": "blue", "Size": 5} to this resource should return "It's a blue banana!".
Try with ((System.ServiceModel.Channels.BufferedMessageData)(((System.ServiceModel.Channels.BufferedMessage)((OperationContext.Current.RequestContext).RequestMessage)).MessageData)).Buffer
it has type System.ArraySegment<byte>
or read WCF + REST: Where is the request data?