I have case class with field AnyContent. I get it from DB as
AnyContentAsText( //some value)
Than when I get it in JSON like text
Json.obj("body"->content.asText)
it returns
[{"body":"AnyContentAsJson({\"ma\":\"some#email.com\"})"}]
When I want get it like JSON
Json.obj(content.asJson)
I get
[null]
How can I get it like JSON but not null of course?
The only way to go from AnyContentAsText to JSON would be to simply do Json.parse(content.asText).
However, it's odd that you're getting a value from your DB as AnyContentAsText. AnyContentAsText and all other subclasses of AnyContent are really intended for the request lifecycle. When you consume a request in a controller method, the first thing you should be doing is parsing your AnyContent into the expected underlying value (text, json, etc.) and then do any business logic/persistence with those underlying values.
If you're receiving AnyContentAsText on the backend, check the request headers that the client sends.
I had forgotten the "Content-Type": "application/json" header on my POST with JSON content. After adding the header, I received AnyContentAsJson on the backend side, as expected.
Related
Is it the recommended way to pass a JSON string as a parameter value in a REST API?
This is the data which I am trying to send :
http://127.0.0.1:8000/v1/product/?productName=&metrics={"memory":2,"disk_space":10}
Here, is it ok to pass the value of metrics as JSON value?
Initially, I tried passing the metrics JSON value in the body. As it is not supported/recommended standard I have removed it.
Is it the recommended way to pass a JSON string as a parameter value in a REST API?
REST is an architectural style and it doesn't enforce (or even define) any standards for passing JSON string as a parameter value.
If you want to send JSON in the query string, you must URL encode it first:
/v1/products?productName=&metrics=%7B%22memory%22%3A2%2C%22disk_space%22%3A10%7D
Alternativelly, you could redesign the parameters to be like:
/v1/products?productName=&metrics.memory=2&metrics.diskSpace=10
If the URL gets too long (or the query gets too complex to be expressed in the query string), you may want to consider POST instead of GET, and then send the JSON in the request payload:
POST /v1/products/search HTTP/1.1
Host: example.com
Content-Type: application/json
{
"productName": "foo",
"metrics": {
"memory": 2,
"diskSpace": 10
}
}
Sending JSON values in GET request is not recommended. You can do it but metrics json can be long and anybody can read the content.
You should use POST request to send parameters such as productName and metrics in the body.
You should refer to this answer for detailed explanation.
For use Content-Type Application Json Please use below line
request.AddParameter("application/json", "{\n\t\"lastName\":\"gaurav.sablok#agarwalpackers.com\"\n}", ParameterType.RequestBody);
This is used with "RestSharp" name spaces
I'm using React and fetch, and I'm trying to send a JSON string to a client's web service, they are expecting an object like this:
{
"id":"1",
"plan_id":"6",
"plan_start_date":"2017-08-02",
"months":"1",
"extra_hours":"4",
"attendees":"1",
"mails":"",
"shopping_cart_id":"0"
}
However, whenever I use JSON.stringify() to generate the JSON string, the result is something like this:
"{
"id":"1",
"plan_id":"6",
"plan_start_date":"2017-08-02",
"months":"1",
"extra_hours":"4",
"attendees":"1",
"mails":"",
"shopping_cart_id":"0"
}"
So when the request is sent, I get back an error stating that the object is not valid.
Is there a way to send the object like on the first example? I've tried manually building the object, but I can't get the key's names to stay in quotes.
EDIT: The code for the call is here:
addToCart(plan) { //Plan is the object with the previous example's structure
fetch("http:ClientWS", {
method: "POST",
body: JSON.stringify(plan) //Produces the "{}" issue
})
.then(response => response.json())
.then(json => {
//Read the response info, here it tells me that the value for 'id' is invalid
console.log(json.datos);
}).catch(function(ex) {
console.log(ex);
});
}
JSON.stringify() does not add extra quotes around the output. If you are seeing those extra quotes, I would say that it implies that the error is somewhere else.
That's because JSON.stringify takes your object and outputs a string variable by concatenating all the properties and values together and inserting some separators. And a string is displayed in quotes, again because it's a string. It's not an object any more. When you send it to the server, the server will see it as a single string value. The fact that the content of the string happens to look like JSON is not taken into consideration.
You do know that JSON and JavaScript objects are essentially the same thing? The stringified JSON that you can see is just a human-readable version of the object structure. It also turns out to be a convenient format in which to serialise objects (from all languages not just JS) for transmission in a HTTP request (or storage in a file or database, among other uses).
So actually when you send your object to the server, do just that - send the object. If you're doing it via ajax, the JS code you're using will generally serialise it for transmission on your behalf. You may have to set the correct content type header. That serialised object inside the HTTP request's body will end up looking a lot like the output of JSON.stringify (if you viewed it in your browser's network tab, for instance), except it won't actually be a string, and the server will interpret it correclty as an object containing multiple properties.
I have this js code
function sendJSon(){
var user = {"user_name" : $("#my_input_field").val()};
$.ajax({
url: 'http://localhost:9000/myAction',
type: 'POST',
data: JSON.stringify(user),
success: function(result) {
$("#my_res_div").html(result);
},
error: function(){
alert("error");
}
});
}
which works perfectly when passed to the application and then goes on success as it was meant to.
But I reached this goal after many tries because at the beginning (browsing this site) I found answers which suggested to specify also content type (application/json or text/javascript) and data type (json) for JSon requests.
I wonder why I get XMLHttpRequest cannot load http://localhost:9000/myAction. Invalid HTTP status code 404 if I specify either content or data types.
This the route line in route file
POST /myAction Application.jsonRequest
The error you're quoting basically means the response to the POST request is a 404 status, which is not an expected value for a POST request (you're sending content, it is illogical for the server to say it can't find that content).
Specifying the dataType field for $.ajax is generally not needed, because it will try to figure it out itself. However, this field should not cause a problem, because it is about parsing the response data, which only happens after the response is received, and the error code indicates a bad response in the first place (meaning it never goes to parsing).
The contentType field for $.ajax is more important for a request. It is a two part string, specifying the type of content being sent and the character set being used to encode the content. So the problem with setting it to either of the values you name is that there is that the character encoding is missing. Another problem is that you're specifying a datatype while at the same time not providing your data in that format. You're explicitly stringifying your content, which means it won't be JSON data.
Ok basically I am sending a POST request with some JSON payload in it to Codeigniter. I use RESTAdapater. JSON get sent there with no key, so I have no access to it.
Here is model:
App.Bookmark = DS.Model.extend({
title: DS.attr("string"),
url : DS.attr("string")
});
Here is controller:
App.BookmarksNewController = Ember.ObjectController.extend({
save: function(){
this.get("model.transaction").commit();
this.get("target").transitionTo("bookmarks");
}
});
In REST implementation in CI that I use standard way to access the post request is $this->input("key"). But when the above request is generated, only raw JSON data is sent. Therefore I don't seem to have a way to reference it in any way.
Take this example:
function post(){
$this->response(var_dump(file_get_contents("php://input")),200);
}
Gives me this output:
string(48) "{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
what I would like to see is:
string(48) payload="{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
Then is server I would be able to access this JSON with something like $this->post("payload").
So 1 of 2. Anyway to wrap the JSON payload with key? Or anyway to access raw JSON data in CI with no key available??
Ok figured it out myself (or rather read properly the examples).
When using Adam Whitney's fork of Phil Sturgeons REST controller for CodeIgniter the JSON payload will be available in $this->_post_args. And in the underlying implementation he uses my already mentioned file_get_contents("php://input").
EDIT: Same convention applies for other type of requests as well, for example DELETE request data will be available in $this->_delete_args. Or $this->_args is the "magic" place where all types of args can be found.
I read about JSON from internet but still i have not got the grasp of it. I am reading this article
http://webcloud.se/log/AJAX-in-Django-with-jQuery/
I could not understood the first part where the function is using JSON
def xhr_test(request, format):
if request.is_ajax():
if format == 'xml':
mimetype = 'application/xml'
if format == 'json':
mimetype = 'application/javascript'
data = serializers.serialize(format, ExampleModel.objects.all())
return HttpResponse(data,mimetype)
# If you want to prevent non XHR calls
else:
return HttpResponse(status=400)
My Main Problems are
From where the function is getting format variable
Does format is json mean that data given to function is json or data which will be recived is json
Can anyone give me simple example that what will be the ouput of this function
data = serializers.serialize(format, ExampleModel.objects.all())
How will I use that data when i get that response in jquery function
If i don't use JSON in above function then how will the input and response back will chnage
Thanks
From where the function is getting format variable
In practice, there are lots of ways this format could be populated. HTTP provides an Accept: header that requests can use to indicate the preferred Content-Type for the response. On the client, you might use xhr.setRequestHeader('accept', 'application/json') to tell the server that you want your response in json format. In practice, though, very few frameworks actually do this. This being django, arguments to view functions are usually set in the urlconf, you might craft a urlconf like this:
urlpatterns = patterns('',
# ...
(r'^xhr_test.(?<format>.*)$', 'path.to.xhr_test'),
)
2 . Does format is json mean that data given to function is json or data which will be recived is json
This particular view doesn't do anything at all with the request body, and is certainly providing a response body in the supplied format
4 . How will I use that data when i get that response in jquery function
Depending on how complicated your request needs to be, you can use jQuery.getJSON, which will pass your callback with regular JavaScript objects that result from parsing the JSON. If you need to do a bit more work to get the request right, you can use jQuery.parseJSON to process the json data, and that will return the same JavaScript objects.
From the urlconf, just like it says in the article right below it.
The query set will be serialized as JSON.
It will be the query set represented as either XML or JSON. python manage.py shell is your friend.
You will decode it, then iterate over it.
You'll need to find some other format to serialize it in instead.