API: return only JSON format - json

I am developing a REST API for my web application for public use.
I am tempted to provide only JSON as format for the response as it is more lightweight than XML (on large traffic, any byte counts).
I think any programming language and platform is able to easily and effectively parse JSON, nowadays.
So, what do you think about providing only JSON and not XML as format for the response?
Thanks,
Dan

Some quantitative data on XML vs JSON here:
http://www.slideshare.net/jmusser/pw-glue-conmay2010
(see slide 11)
From the 2,000 API's they checked, 45% of them supported JSON in 2010 and the numbers we're quite quickly rising. With a total of 132 (of those 2,000) that only accept JSON. No statements we're made about the amount of XML-only API's.

That's pretty much how I work all the time. I found that Google Chrome displays JSON responses out-of-the-box, while XML responses require me to "view source" or cheat using Content-Type: text/plain. I also find JSON very handy when building command-line mini-tools to interact with web/comet servers, message buses, etc., because there is so much less typing and the typing you have to do is so much easier. For instance try timing yourself as you type this on the command line:
sendmsg foobar/queue1 '<msg><labels><rows><row>a</row><row>b</row><row>c</row><row>d</row><row>e</row></rows></labels></msg>'
vs. this:
sendmsg foobar/queue1 '{"labels":["a", "b", "c", "d", "e"]}'

Related

How to convert Chrome's Request Payload into JSON?

When I'm checking web requests in Chrome's DevTools on Mac (Network tab), I've got the Payload in the following format:
7|0|6|https://www.example.com/app/Basic/|00D1D071AC218DFE91521C012683E911|com.optionfair.client.common.services.nongenerated.RefreshService|getCometUpdates|I|J|1|2|3|4|3|5|6|6|173|VvAwAqy|o$UN|
which is basically separated by vertical bar character (|).
How I can copy or convert above payload from Chrome into some meaningful format such as JSON? Any ideas?
Btw. In this question it looks fine on the screenshot, but in my case, I don't have view parsed and it doesn't look like JSON format at all.
Using Google Chrome on Mac (Version 57.0.2987.133, 64-bit).
Reproducible steps:
Go to this page.
Open DevTools on Network/XHR tab and look for refresh requests.
My goal is to reuse/replicate the POST data in Request Payload in the command-line tool such as curl so it can be recognized (not necessary on the page mentioned above, but I'd like to know the general approach to deal with this blob format). I would expect JSON format, but it's not.
Here you need to look at the request header content-type to determine how this request was encoded before knowing what might parse it:
This is GWT RPC, so it can include serializations of built-in and custom Java Objects, where knowledge of the class is in both server-side Java and transpiled Java running on the client via Google Web Toolkit.
There is no reason for Chrome to understand this format directly, and it need not have a JSON or XML cannonicalization. Fully interpreting these calls to the extent it is possible on the client may require disassembly or introspection tricks against the transpiled client code, assuming the program wasn't transpiled with source maps.
Without digging into the client code, one can interpret the literal rpc while guessing at or probing the definition of classes and their methods by modifying the call.

What is JSONC? Are JSONC and JSON-C different?

Recently came across the term JSONC in a YouTube API. I browsed the Web, but found nothing much about it. Can someone explain whether these two are the same or different?
There is also jsonc aka "JSON with comments", created by Microsoft and used by Visual Studio Code. The logic for it can be found here, alas without exhaustive specification (though I'd like to be proven wrong on this).
On top of that there is this project with an actual specification which is also called jsonc, but also does far more than just adding comments.
While there definitely is a use for these technologies, some critical thinking is advised. JSON containing comments is not JSON.
JSON-C seems to just be a variation of JSON mainly targeted at C development. I.e., from the open source docs, "JSON-C implements a reference counting object model that allows you to easily construct JSON objects in C, output them as JSON formatted strings and parse JSON formatted strings back into the C representation of JSON objects."ref^1
From the YouTube API perspective (specifically, version 2, not the new version 3), The JSON-C response is just a condensed version of the JSON response (removing "duplicate, irrelevant or easily calculated values").ref^2
Why would the JSON response have "duplicate, irrelevant or easily calculated values" values anyway? Because it is converting the original ATOM XML format directly to JSON in a loseless conversion. You can find out more details here.
However, I would suggest using version 3 of the YouTube Data API. It is much easier to use. =)
JSONC is an open-source, Javascript API created by Tomás Corral Casas for reducing the size of the amount of JSON data that is transported between clients and servers. It uses two different approaches to achieve this, JSONC.compress and JSONC.pack. More information can be found on the JSONC Github page:
https://github.com/tcorral/JSONC

Consuming JSON WCF on Silverlight

I'm want to try changing a SOAP WCF to accept requests and return results in JSON format to make the data traffic less bulky.
I see that JSON requests functions looks like this:
wcfClient.OpenReadAsync(http://yourUrl.com/wcf/service1.svc/GetEmployees)
and do the regular SOAP requests functions instead that looks like :
wcfClient.GetEmployeesAsync();
1) For JSON results, do you need to parse them into an object or is it automatically parsed like SOAP?
2) Is there a way to do this without doing too much work like changing every single WCF calls in the project to looks "JSON-ish"?
To complement Davut's answer - WCF does support building RESTful services, although I agree that the ASP.NET Web API framework in general easier to use than WCF. JSON.NET is a great library, and it has nice deserialization capabilities (e.g., it can easily take the JSON which represent the list of Employee objects and convert them into the actual List<Employee> instance)
But for completeness sake, if you want to use a "normal" WCF client to access WCF-based services which return JSON, you can do it. It's not too straightforward, but you can do that by using a new encoder and behavior which does the conversion. The post at http://blogs.msdn.com/b/carlosfigueira/archive/2010/04/29/consuming-rest-json-services-in-silverlight-4.aspx talks more about it, and has a pointer to a code sample.
In short, it's possible to consume JSON using a WCF client in Silverlight, but due to its complexity it's usually not done, and Davut's option (use a HTTP client such as WebClient to download JSON, then a library such as JSON.NET to parse it into objects) is preferred.
Firstly the idea "make the data traffic less bulky." is good.
Especially for Mobile devices. Beside this don't think that WCF xml causes network issues for PC. XM is the one of most compressible format. By WCF binary it goes as compressed.
For "Is there a way to do this without doing too much work?"
Yes there is a way name on it RESTFul Services(Restless Services). Now Microsoft directly support it by WEBApi.
Also you may use ODATA for filtering,ordering operations
Here are some links,
http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webgetattribute.aspx
http://blogs.msdn.com/b/rjacobs/archive/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4.aspx
ODATA
http://www.odata.org/documentation/uri-conventions#FilterSystemQueryOption
A few practice notes,Some restrictions:
EntityFrameWork entities derived from EntityObject which has IsReferenceType attribute doesn't allow you to JSON serialize. ( I produced POCO objects using an automapper mapped them and serialized json)
WEBAPI support you much think such as WebGet,WebInvoke GetXML Give JSON ,ODATA features(just select and format not allowed.)
Note:In your web request's header you should accept text/json to get really json.
"For JSON results, do you need to parse them into an object or..."
I can say you should try JSON.NET it's portable library works everywhere. When you deserialize with a generic function it returns you the collection you expect.
Hope it helps someone. While discovering these stackoverflow helped me like an assistant.

POSTing data to a server with jQuery - why use JSON?

All over the net I see examples of using jQuery to make AJAX POSTs of JSON encoded data to a server. What is the point of encoding the data in JSONfirst? Why not just send it as the default data type application/x-www-url-form-encoded which would save having to parse JSON data on the server?
Couple of reasons. One, it's very easy to turn a JavaScript object into JSON, while it takes effort to encode it as x-www-url-form-encoded. Also, x-www-url-form-encoded isn't really used that much any more. Besides the couple of input types that require a form, most things use AJAX nowadays. Also, JSON is much easier to debug because it's legible.
First, you don't have to use json. If you are more comfortable using any other format, then use it.
But keep in mind, it's all strings. And sometimes it makes sense to use a format like JSON. What happens if you form is dynamic, and you enter multiple instances of the same thing (e.g. name1, name2, name3....)? It's really easy to iterate over such things with JSON. And JSON parsers are readily available for all platforms, so it's not like using it is a hinderance on any platforms. Plus, if both submissions and responses use the same format, there is the benefit of consistency for the data in requests and responses.
JSON is short for JavaScript Object Notation, and is a way to store information in an organized, easy-to-access manner.In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner.
We use JSON encoding to organize stored information.
Example:
var jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};
To access the information stored in json, we can simply refer to the name of the property we need.
Result:
document.write('Json is ' json.age); // Output: Jason is 24

Normal form submission vs. JSON

I see advantages of getting JSON response and formatting in client side but are there any advantages by using JSON for form submission compared to normal submission?
One thing comes to mind when dealing with POST data is useless repetition:
For example, in POST we have this:
partners[]=Apple&partners[]=Microsoft&partners[]=Activision
We can actually see, that there is a lot of repetition here, where as when we are sending JSON:
{"partners":["Apple","Microsoft","Activision"]}
59 characters versus 47. In this small sample it looks miniscule, but these savings could go up and up, and even several bytes will save you some data. Of course, there is the parsing of data on server side, which could even out the differences, but still, i saw this sometimes helping when dealing with slower connections (looking at you, 3G and EDGE).
I didn't see any mention of file submission so I thought I'd chime in. FormData seems to be the standard way of submitting files to a server over AJAX. I didn't come across any solutions using JSON but there might be a way to serialize/deserialize files ...
It probably depends on your server side application. You are usually posting data to servers using POST, so how do you format underline data depends on how do you want for your server to process it. POST provides some form of key->value protocol, while in JSON you can put more than that. You can also transfer json using GET by placing it in url.
You must look on json as a way how data is written, while normal submission with POST should give you just a way how you transport data(of course you can abuse key->value feature of it for ordering your data).
There exists protocols on top of HTTP, that could help you define interface to your web application. One good example is RESTfull http://en.wikipedia.org/wiki/Representational_state_transfer
Specifically for submitting forms, I don't see any advanatages, POST was designed for this in a first place. There are cases where you want to transmit not only data from form, but also some metadata in this case json might help you by encoding form data(with metadata) in some json format, but at the end you will be still abusing POST for transferig this json data.
Hope I answered your question.
I don't see any apparent advantages for basic form submission. But when it comes to handling complex structures you'll start to realize the advantage of organizing your data.
So if you have a simple contact form (name, email, message) stick with normal form POSTing. But think about submitting a complete user's CV for example, it's very annoying to handle the massive amount of variables in your server-side script.
Here's an example for using JSON with PHP
//Here are the submission data
{
"personalInformation": {
"name": "hey",
"age": "20"
},
"education": {
"entry1": {
"type": "Collage",
"year": "2012"
},
"entry2": {
"type": "Highschool",
"year": "2010"
}
}
}
$CV_Data = json_decode($_POST['json_form'], true);
$CV_Data['personalInformation']['name'];
$CV_Data['personalInformation']['age'];
//Or you can loop
foreach($CV_Data['education'] as $entry){
$entry['type'];
$entry['year'];
}
As you can see, using JSON here makes it a lot easier for you to work on your data.
I am actually wrestling with the same problem. My use case requires that a potentially complex tree to be posted to the server. Some framework are able to decode two dimensional arrays as form attributes (Spring WebMVC is one I know of). Even so, this only helps you in the specific case when you are sending a nested array. The inherent nature of name-value-pair makes it unsuitable for transmitting a tree more than one level deep. In the past, I have used hacks like sending URL-encoded JSON as attribute value:
val0=%7B%22name%22%3A%22value%22%7D&val1=something&val2=something+else
However, this approach gets messy and difficult to debug when the object becomes more complex. In addition, many frameworks provide tools that automagically map JSON form post to objects (e.g.: Jackson for Java), it seems obtuse not to take advantage of these tools.
So ultimately, the choice rests on the complexity of the object you are sending. If the object is limited to one level deep, use straight name-value-pair; if the object is complex and involves a deeply-nested tree, use JSON.