JSON stands for JavaScript Object Notation. But how come languages like php, java, c etc can also communication each other with json.
What I want to know is that, am i correct to say that json is not limited to js only, but served as a protocol for applications to communicate with each other over the network, which is the same purpose as XML?
JSON cannot handle complex data hierarchies like XML can (attributes, namespaces, etc.), but on the other hand you don't get the same overhead with JSON as you get with XML (if you don't need the complex data structures).
Since JSON is plain text with a special notation for JS to interpret, it's an easy protocol to adopt in other languages.
It is easy for a JS script to parse JSON, since it can be done using 'eval' in which the JS enginge can use its full power.
On the other hand, it is more complicated to generate JSON from within JS. Usually one uses the JSON package from www.json.org in which an object can easily be serialised using JSON.stringify, but it is implemented in JS so its not running with optimal performance.
So serialising JSON is about the same complexity using JS as when using Java, PHP or any other server side language.
Therefore, in my opinion, JSON is best suited when there is asymmetry between produce/consumer e.g. a web server that generates a lot of data that is consumed by the web application. Not the other way around.
But! When one choses JSON as data format it should be used in both directions, not XML<>JSON. Except for when simple get requests are used to retrieve JSON data.
yes, JSON is also wildly used as a data exchange protocol much like XML.
Typically a program (not written in JavaScript) needs a JSON library to parse and create JSON objects (although you can probably create them even without one).
Your right - it's a light weight data interchange format -- more details at: http://www.json.org
You are completely correct. JSON definition of how data should be formatted. It is more light weight than XML and therefore well suited to things like AJAX where you want to send data back and forth to the server quickly.
Related
I created the following Thrift Object:
struct Student{
1: string id;
2: string firstName;
3: string lastName
}
Now I would like to read this object from JSON. According to this post this is possible
So I wrote the following code:
String json = "{\"id\":\"aaa\",\"firstName\":\"Danny\",\"lastName\":\"Lesnik\"}";
StudentThriftObject s = new StudentThriftObject();
byte[] jsonAsByte = json.getBytes("UTF-8");
TMemoryBuffer memBuffer = new TMemoryBuffer(jsonAsByte.length);
memBuffer.write(jsonAsByte);
TProtocol proto = new TJSONProtocol(memBuffer);
s.read(proto);
What I'm getting is the following exception:
Exception in thread "main" org.apache.thrift.protocol.TProtocolException: Unexpected character:i
at org.apache.thrift.protocol.TJSONProtocol.readJSONSyntaxChar(TJSONProtocol.java:322)
at org.apache.thrift.protocol.TJSONProtocol.readJSONInteger(TJSONProtocol.java:698)
at org.apache.thrift.protocol.TJSONProtocol.readFieldBegin(TJSONProtocol.java:837)
at com.vanilla.thrift.example.entities.StudentThriftObject$StudentThriftObjectStandardScheme.read(StudentThriftObject.java:486)
at com.vanilla.thrift.example.entities.StudentThriftObject$StudentThriftObjectStandardScheme.read(StudentThriftObject.java:479)
at com.vanilla.thrift.example.entities.StudentThriftObject.read(StudentThriftObject.java:413)
at com.vanilla.thrift.controller.Main.main(Main.java:24)
Am I missing something?
You are missing the fact, that Thrift's JSON is different from yours. The field names are not written, instead the assigned field ID numbers are written (and expected). Here's an example for Thrift's JSON protocol:
[1,"MyService",2,1,{"1":{"rec":{"1":{"str":"Error: Process() failed"}}}}]
In other words, Thrift is not intended to parse any kind of JSON. It supports a very specific JSON format as one of the possible transports.
However, depending on what the origin of your JSON data is, Thrift can possibly still help you out, if you are able to use it on both sides. In that case, write an IDL to describe the data structures, feed it to the Thrift compiler and integrate both the generated code and the neccessary parts of the library with your projects.
If the origin of the JSON lies outside of your reach, or if the JSON format cannot be changed for some reason, you need to find another way.
Format and semantics are different beasts
To some extent, the whole issue can be compared with XML: There is one general XML syntax, which tells us how we have to fomat things so any standard conformant XML processor can read them.
But knowing the rules of XML is only half the answer, if we get a certain XML file from someone. Even if our XML parser can read the file successfully, because it is well-formed XML, we need to know the semantics of the data to really make use of what's within that file: Is it a customer data record? Or is it a SOAP envelope? Maybe a configuration file?
That is where DTDs or XML Schema come into play, they exist to describe the contents of the XML data. Without knowing the logical structure you are lost, because there are myriads of possible ways to express things in XML. And exactly the same is true with JSON, except that JSON schema descriptions are less commonly used.
"So you mean, we need just a way to tell Thrift how the JSON is organized?"
No, because the purpose and idea behind Thrift is to have a framework to de/serialize things and/or implement RPC servers and clients as efficiently as possible. It is not intended to have a general purpose file parser. Instead, Thrift reads and speaks only its own set of formats, which are plugged into the architecture as protocols: Thrift Binary, Thrift JSON, Thrift Compact, and a few more.
What you could do: In addition to what I said at in the first section of my answer, you may consider writing your own custom Thrift protocol implementation to support your particular JSON format of choice. It is not that hard, and worth a try.
I'm new to Java. I want to send an array (ArrayList) of objects over the network via Java Web Service to my Silverlight app. This ArrayList contains custom class objects:
ArrayList<SVNSearchResult> results
so I'm thinking the best way is to serialize this to an XML String and on the Silverlight part, use LinQ to parse it. If there's a better way to send it please let me know. Thanks.
XML is a good fit for this. JSON would be one of the other usual suspects these days.
Whatever format you end up choosing, make sure you get the encoding right.
For a starter, try JSON. It has a network-efficient format, and is supported by any major language in the world.
XML is only my second choice as it is more complicated to generate/parse and is more verbose.
Just wondering which is best here. I want to output data from a table in my DB then put a lot of this data into a html table on the fly on my page. I'm working with Java on the server side. Basically I pull the results form the DB and have the raw data..just what next?
There is a chance I may want to take data from multiple tables in order to combine it into one table for my site.
I retrieve the results of the query from the DB, now do I create a text from it in the form of json which I can parse as json using jquery upon the return of the object to my browser?(kind of a sub question of this question: Is just using a stringbuilder the correct way to make a json object to output?)
Or..
Should I build the HTML as a string and output that to the browser instead?
Which is better and why?
I've built entire pages from JSON data on the client. It reduces the redundancy of repeating HTML and can lead to better performance, depending on the complexity of your HTML.
I had large a catalog that used multiple tabs for different sections. Sending it all to the client as JSON and generating the resulting HTML was way faster than downloading the equivalent HTML.
What you lose, of course, is SEO. Search engines won't be able to see the Javascript-generated output. There are ways around this, using hash URL techniques.
I used to be in favor of generating HTML on the server so that the client can be dumb and simply inject dynamic content. The pragmatic real world advantages for our small team was that we needed to be experts at fewer different technologies. We focused on the middle tier and back end and spent less time on the front end.
Lately, with tools like jQuery, it is easier and easier to do more robust client stuff without having to increase the dev bandwidth much. From a client side, I can say building dynamic HTML from JSON using jQuery isn't that hard.
From the server side, I'm sure there are tools to serialize to JSON. I wouldn't roll your own with StringBuilder. Sorry, I'm not a Java guy so don't have a recommendation.
I'd go with JSON if I knew I had anything more than just static views of the data in mind later on.
But if it's just so that you can see what the result was, and don't care too much for the data then I'd go with the straight forward HTML output.
For actually generating the JSON server-side, there are a number of libraries you can use. org.json is the canonical one, but I prefer Stringtree personally.
Is there any way to deserialize in PHP an object serialized in Java? IE If I have a Java class that implements Serialization and I use an ObjectOutputStream to write the object, and convert the result to a string, is there a way in PHP to take that string and create a similar object representation from it?
What does the Java Serialized data look like?
Response:
���sr�com.site.entity.SessionV3Data���������xpsr�java.util.HashMap���`��F�
loadFactorI� thresholdxp?#�����w������t� sessionIdt�0NmViMzUxYWItZDRmZC00MWY4LWFlMmUtZjg2YmZjZGUxNjg5xx
:)
I would heavily recommend you don't do this. Java serialization is meant for a Java instance to both save and load the data (for either transmission to another Java application or persistence between invocations of the same application). It was not at all meant to be a cross-platform protocol.
I would advise you to make an API adapter layer between the two. Output the contents of your Java object to a format you can work with in PHP, be it XML, YAML, or even a binary format (where you could use DataOutputStream).
What is the easiest way to eat soup with chopsticks when the soup was put in a bowl with a ladle? Put the soup in a cup and discard your chopsticks, because chopsticks are a poor choice for aiding in the consumption of soup. A cup (ubiquitous) eliminates external dependencies except for "mouth" and "opposable thumbs", both of which come with the standard library of humans.
A more elegant solution would be to encode that Java object with a JSON Serializer or XML serializer. Protocol Buffers or any other intentionally cross-language serialization technique would work fine plus Protocol Buffers can efficiently encode binary data.
Some time ago i did something simillar. However i didn't make PHP read "Java serialize" format. I did the oposite, that is, made Java serialize itself to a "PHP serialize" format. This is actually quite easy. Have look at PHPSerializedResponseWriter class that is a part of Solr package:
https://github.com/terrancesnyder/solr-analytics/blob/master/solr/core/src/java/org/apache/solr/response/PHPSerializedResponseWriter.java
...then all you have to do is just read the string and call:
$result = unserialize($string);
From comments in the online PHP manual, there is a Java class that serializes to the PHP serialization format that you can look into. Then you can unserialize the data using the standard PHP functionality.
Is it possible to use one of the more common cross platform data formats like JSON to communicate between your Java app and PHP? PHP has plenty of parsers for those formats. Check out json_decode for an example.
Is there any way to deserialize in PHP
an object serialized in Java?
Yes. The question is, should you? Exporting the Java object as XML or JSON probably makes more sense.
The following SO question might also help.
Dynamically create PHP object based on string
I'm looking for a good web framework for compositing multiple JSON sources fetched with HTTP requests in to static HTML. I am not looking to do this on the client-side (browser, javascript), I am looking for the best server-side solution.
So, what I need to do is:
Fetch several different JSON documents over HTTP
Format that JSON as HTML content, mostly with templates but some dynamic custom HTML
Basic login/logout/preferences customization, nothing major
Mostly stateless pages; what state there is, comes already in the JSON
User / search engine friendly / bookmarkable URLs; should be customizable accurately
How I'd like to do it:
A lean solution, perhaps just a template engine
HTML templates that have no custom syntax over HTML/XML, like Wicket and almost like Tapestry
Application server that is scalable and utilizes multiple CPUs properly (for example, a single Python process does not)
Preferably Java, but if Java doesn't have anything that fits, willing to consider others
As for the template part, if this were to be in JavaScript in the browser, something like PURE would be my tool of choice.
You might want to check out RESTx. That's an open source platform for the easy creation of RESTful resources. It allows you to write custom data access and integration logic in either Java or Python. Getting data from multiple sources and combining them is what it's made for, so this should be a pretty close fit. Data output is rendered according to what the user requested. For example, a further JSON data source, or the same data rendered in HTML.
The HTML rendering is currently according to a built-in template. However, that should be easy enough to modify. I'm one of the developers on that project, so if you need some special template functionality, let me know and I will see what I can do.
To give you an example: Assume you have two JSON resources, in your code you would write this (I'm giving a Python example here, but the Java example would look very similar):
status, data_1 = accessResource("/resource/some_resource")
status, data_2 = accessResource("/resource/some_other_resource")
# data_1 and data_2 now hold a dictionary, list, etc., depending on the JSON
# that was returned.
# ... some code that combines and processes the data and produces a dict or list
# with the result. The data object you return here is then automatically rendered
# in either HTML or JSON, depending on the client request.
return Result.ok(data)
Also take a look at the example for some simple data integration here.
I think that the only framework you need is a library that reads json. The templates can very well be standard jsp pages.