I am using Resteasy and GWT. For certain reasons, as many others have similar motivations, I am not using GWT-RPC for some of the functionality of the software I am working on.
I need to pass POJOs between GWT client and server by marshalling/demarshalling the POJOs into/from JSON.
OK, easier said than done because I need the POJO-JSON converters on both sides to match.
Q1. Is there a standard POJO notation in JSON? Is there an ietf RFC or ISO or ECMA that specifies the format of POJO notation in JSON? Or is it a free for all, libertarian anarchy?
Q2. Do Jettison and Jackson (when used with JAXB) and Autobeans produce the same JSON for POJOs?
Q3. This is the most crucial question. You can ignore the other questions above but you MUST answer this. Give me a combination pair of server-side and GWT client side JSONizer/deJSONizer that works together. For example, can I use Autobeans on client-side and use JAXB-jettison on server side and expect the JSONized POJO notation to be the same?
Q4. Is it possible to use JAXB-Jettison or JAXB-Jackson on GWT client-side by including the java source code for JAXB, Jettison/Jackson in the whatever.gwt.xml file? Are there parts of JAXB, Jettison/Jackson source code that might e.g., depend on reflection, or non-serializable, etc that would not make it possible to use JAXB + Jettison/Jackson in GWT client code? If possible, please explain how?
~
I should clarify concerning Q1:
I am not asking about RFC for JSON. I am asking about JSON POJO format. When a POJO is converted to JSON, everybody does it their own way - so, I am thinking that there should be an RFC to standardise the way and format a POJO is converted to JSON. Is there a standard or not? !!I hope your answers should not quote me the RFC for JSON!!
~
What about
Someone needs to tell me about
badgerfish on GWT client
and GWT client-server matched JSON-RPC.
There is no standard for mapping, but I would claim there is obvious simple mapping, given simplicity of JSON format, and de facto standard of Java Beans (i.e. mapping of set/get methods to logical property names). One of few exceptions is Jettison.
Jettison is not as much a JSON/POJO library as it is JSON<->XML library: it converts JSON to XML API calls (and vice versa), to allow use of XML tools such as JAXB for XML data binding, on JSON. But the cost here is that JSON it produces and consumes has extra complexity which is only needed to work with XML APIs. And this is what makes it non-standard compared to the usual straight-forward bindings like used by Jackson, GSON, Flex-json and other "native" JSON libs.
I would recommend not using Jettison unless you really, really must for some reason. Not even if you produce both XML and JSON -- usually you are better off mapping JSON to/from POJOs using JSON tools, and XML separate to/from POJOs (using JAXB etc).
Jettison was intended to bridge the gap between (then) more mature XML tools and newish JSON format. But there isn't much benefit nowadays when there are dozens of mature JSON libraries available.
JSON is just a subset of JavaScript, it was "invented" by Douglas Crockford. Here is the RFC for application/json: http://www.ietf.org/rfc/rfc4627.txt?number=4627. So any of your server side solutions should create the same result.
We are using RestyGwt ( http://restygwt.fusesource.org/ ) on the clientside and it works like charm. Its JSON encoding style is compatible with the default Jackson Data Binding so it should work with Jackson as well.
Related
For example, we have 2 microservices written by Java, C#.
Front-end with Typescript.
Java uses camel case and has one GET with query params and JSON response,
C# uses pascal case and has one GET with query params and JSON response.
TypeScript uses camel case and both GETs.
first question is:
Do we need use different cases for query params and JSON inside GET (C# - pascal case and Java - camel case) or we need to use one convention for all sources?
Also query params and JSON must have the same cases, mustn't it?
second question is:
If I have already had some API with query params and JSON in pascal case. Need I to write some "normalizer" to map pascal case to camel case?
Just from my point of view, frontend, backend and API can have different conventions but developers need to map data which is coming from other place. But it can be overweight to write many "serializations" on frontend for all data from API.
From my experience I developed the project there all parts used camel case, but also I developed the app where backend and API used pascal case and frontend used camel case but I had some issues from the last one.
Just want to see your opinion about this theme and know how do you make it? Would be glad to see your own examples and experiences. Thanks a lot!
We had the same question in the project I am working on right now, several weeks ago and considered those points:
We wanted 'public facing' entities to have the same convention (endpoints, JSON DTOs etc.)
We wanted to distinguish between functions/methods and variables
We don't wanted to influence the learned behaviour inside a technology
We further considered that snake_case is better readable by humans then camelCase or PascalCase (https://en.wikipedia.org/wiki/Camel_case#Readability_studies).
So we agreed on keys in JSONs being snake_case for readability as well as variable names as long as the language is not much opinionated on that (i.e. we adopted snake_case for JavaScript, but not for Java).
Further we agreed on endpoints being camelCase, since it is a method/function like construct. We chose camelCase over PascalCase, since PascalCase could be misleading in regards to classnames typically being PascalCase. We even took camelCase for JavaScript functions.
That works out fine so far. Hope that helps.
I'm using GWT-RPC to get the client data and my requirement is to parse the payload to retrieve the data inside. I need to log or persist this data for metrics/monitoring purpose.
I'm using the Servlet Filter to intercept the HTTP requests. I can see that the request looks something like this -
5|0|7|http://localhost:8080/testproject|
29F4EA1240F157649C12466F01F46F60|com.test.client.GreetingService|
greetServer|java.lang.String|myInput1|myInput2|1|2|3|4|2|5|5|6|7|
Is there any standard mechanism to parse this data? I'm afraid writing my own code to parse this is not a good solution as this request payload is going to be complex when we pass custom objects to/from RPC and GWT-RPC internal parsing mechanism could change in future, which can break my code. I came across this, but not sure if it is robust/maintained.
Is there any alternative? Any pointers will be appreciated.
Use the RPC class from GWT.
You'll have to provide the serialization policy, whose strong name is passed in a request header.
Decoding responses is harder. You can use com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.ResponseReader along with a com.google.gwt.user.client.rpc.impl.ClientSerializationStreamReader but you'll need to have the JsParser from gwt-dev.jar in the classpath; and you cannot have gwt-dev.jar in a web application as it contains the servlet API (among others); so you'll have to extract the relevant classes from gwt-dev.jar to use them in your web app.
Note that in both cases, you'll reconstruct the same objects as will be deserialized for processing the request "for real", or were serialized as the result of the request processing.
All-in-all, you'll probably have better luck and better performances with using AOP on the methods of your RemoteServiceServlets.
I'm not sure, if that is what you're looking for, but a standard way to log the parsed parameters would be to override AbstractRemoteServiceServlet's onAfterRequestDeserialized(RPCRequest rpcRequest): RPCRequest contains the service method, with all its parameter values, the parsed RpcToken etc. in the form of nice Java objects.
I was wondering if someone could explain the differences in a SOAP request/response of a Web service with the following wsdl binding style/use:
Document/literal
RPC/literal
wrapped document style
Thanks in advance
This article from IBM DeveloperWorks [Which style of WSDL should I use?] has an excellent explanation of the differences between these binding styles. In a nutshell, the only differences are the values of the SOAP binding "style" attribute ("rpc" or "document") in the WSDL file and the way the message arguments and return values are defined (and thus how they appear in the SOAP messages themselves):
[Note the reordering of items from the question to emphasize relationships]
RPC/literal - WSDL message element defines arguments and return value(s) of operations.
PROS: simple WSDL, operation name appears in SOAP message, WS-I compliant.
CONS: difficult to validate since arguments are defined in WSDL not XSD.
Document/literal - WSDL message parts are references to elements defined in XML Schema.
PROS: easily validated with XSD, WS-I compliant but allows breakage.
CONS: complicated WSDL, SOAP message does not contain operation name.
Document/literal wrapped (or "wrapped document style") - WSDL message input has single input and output parameters and input refers to XSD element with same local name as WSDL operation.
PROS: easily validated, SOAP message contains operation name, WS-I compliant.
CONS: most complicated WSDL (not an official style but a convention).
In my experience, #3 (Document/literal Wrapped) is very common in large enterprise projects because it is both Microsoft and OSS friendly and it is well suited for a top-down development model (e.g. WSDL/XSD first, then generate code artifacts). Microsoft invented it [1] and popular Java/OSS tools (Axis2, JAX-WS) support it explicitly.
The "real world" difference likely comes down to which styles are supported — and how well — by the tools of your choice.
which one best for iphone application ? JSON is different from these three webservice methods ?
could you please suggest me..
JSON is just a serialization format, whereas SOAP and XML-RPC are more like request-response exchange protocols. This basically allows you to invoke remote methods.
In other words, you cannot really compare these. If you're building RESTful applications, serialization to JSON (or plain old XML, for that matter) should be just fine. And please for all good there is in the world (this is subjective, inflammatory and argumentative) do not use either SOAP or WS-* unless it's absolutely neccessary.
Agreeing with Anton, JSON is a serialization format (like XML or CSV). JSON is typically lighter weight than XML, but there are some data structures that don't lend themselves to JSON serialization.
If you're using a RESTful interface you can, but not recommended, alternate between JSON and XML depending upon the service call. I've found using XML for the serialization method to fit nicely into the iPhone SDK since it provides native XML stream parsing in NSXMLParser.
JSON could be one of the formats a REST request gets its answer into.
JSON, being directly parsable in a browser environment, is the best format to communicate in a web application heavily interactive. REST is a way to define a clever GET or POST request to a server than can reply in various formats: xml, plain text, json.
For a web app or an iPhone app, I'd go with it.
It needs the less libraries (or none at all) goes well with async http requests, has the smallest overhead and doesn't go great lengths like SOAP and XML-RPC resolving problems web apps usually DO NOT have: strong typing, mainly.
Hessian is much better communication protocol than XML and/or JSON. Being a binary format it is even more compact, and with a strict format parsing is much faster. And it also consumes much less memory. As a bonus a simpler parser also means your application is more secure.
As a bonus there are already frameworks for Java, .NET and PHP to expose a web service. Truly easy. Asume you have this Java interface:
public interface Test {
public String getGreeting();
int addNumbers(int a, int b);
}
Then implementing it on the server using Hessian is a snap:
public class TestSevlet extends HessianServlet implements Test {
public String getGreeting() { return "Hello World!"; }
public int addNumbers(int a, int b) { return a + b; }
}
The server can also with just as easily be implemented in .NET or PHP for example. There are numerous of Hessian implementations available.
On the iPhone side the Java interface need to be translated into an Objective-C protocol:
#protocol Test
-(NSString*)getGreeting;
-(int)addNumbers:(int)a :(int)b;
#end
And then using [HessianKit][2] for getting a proxy for the service is almost as easy:
id<Test> proxy = [CWHessianConnection proxyWithURL:serviceURL
protocol:#protocol(Test)];
NSLog(#"Greeting: %#", [proxy getGreeting]);
NSLog(#"The answer: %d", [proxy addNumbers:40 :2]);
In this short answer the method names are not quite Obj-C-ish. This is because by default HessianKit uses Java's naming conventions. This can be overriden in HessianKit by providing method, and type name translations. So that both the Java and the Obj-C sides on the connection feels 100% at home. For example:
[CWHessianArchiver setClassName:#"com.mycompany.Test"
forProtocol:#protocol(CWTest)];
[CWHessianArchiver setMethodName:#"AddNumbers"
forSelector:#selector(addInt:toInt:)];
I'm developing a new application for the company.
The application have to exchange data from and to iPhone.
Company server side uses .NET framework.
For example: the class "Customer" (Name, Address etc..) for a specific CustomerNumber should be first downloaded from server to iphone, stored locally and then uploaded back to apply changes (and make them available to other people). Concurrency should not be a problem (at least at this time...)
In any case I have to develop both the server side (webservice or whatever) and the iPhone app.
I'm free to identify the best way to do that (this is the application "number ONE" so it will become the "standard" for the future).
So, what do you suggest me ?
Use SOAP web services (XML parsing etc..) or user JSON ? (it seems lighter...)
Is it clear to me how to "upload" data using SOAP (very long to code the xml soap envelope ... I would avoid) but how can I do the same using JSON ?
The application needs to use date values (for example: last_visit_date etc..) what about date in Json ?
JSON has several advantages over XML. Its a lot smaller and less bloated, so you will be passing much less data over the network - which in the case of a mobile device will make a considerable difference.
Its also easier to use in javascript code as you can simply pass the data packet directly into a javascript array without any parsing, extracting and converting, so it is much less CPU intensive too.
To code with it, instead of an XML library, you will want a JSON library. Dates are handled as you would with XML - encode them to a standard, then let the library recognise them. (eg here's a library with a sample with dates in it)
Here's a primer.
Ah, the big question: JSON or XML?
In general, I would prefer XML only when I need to pass around a lot of text, since XML excels at wrapping and marking up text.
When passing around small data objects, where the only strings are small (ids, dates, etc.), I would tend to use JSON, as it is smaller, easier to parse, and more readable.
Also, note that even if you choose XML, that does not by any means mean you need to use SOAP. SOAP is a very heavy-weight protocol, designed for interoperability between partners. As you control both the client and server here, it doesn't necessarily make sense.
Consider how you'd be consuming the results on the iPhone. What mechansim would you use to read the web service response? NSXMLParser?
How you consume the data would have the biggest impact on how your serve it.
Are JSON and SOAP your only options? What about RESTful services?
Take a look at some big players on the web that have public APIs that are accessible by iPhone clients:
Twitter API
FriendFeed API
Also, review the following related articles:
How to parse nested JSON on iPhone
RESTful WCF service that can still use SOAP
Performance of REST vs SOAP
JSON has following advantages:
it can encode boolean and numeric values ... in XML everything is a string
it has much clearer semantics ... in json you have {"key":"someValue"}, in XML you can have <data><key>someValue</key></data> or <data key="someValue" /> ... any XML node must have a name ... this does not always make sense ... and children may either represent properties of an object, or children, which when occuring multiple times actually represent an array ... to really understand the object structure of an XML message, you need its corresponding schema ... in JSON, you need the JSON only ...
smaller and thus uses less bandwidth and memory during parsing/generation ...
apart from that, i see NO difference between XML and JSON ... i mean, this is so interchangable ... you can use JSON to capture the semantics of SOAP, if you want to ...
it's just that SOAP is so bloated ... if you do want to use SOAP, use a library and generators for that ... it's neither fun nor interesting to build it all by hand ...
using XML RPC or JSON RPC should work faster ... it is more lightweight, and you use JSON or XML at will ... but when creating client<->server apps, a very important thing in my eyes, is to abstract the transport layer on both sides ... your whole business logic etc. should in no way depend on more than a tiny interface, when it comes to communication, and then you can plug in protocols into your app, as needed ...
There are more options than just SOAP vs JSON. You can do a REST-based protocol (Representational State Transfer) using XML. I think it's easier use than SOAP and you get a much nicer XSD (that you design.) It's rather easy for almost any client to access such services.
On the other hand, JSON parsers are available for almost any language and make it really easy to call from JavaScript if you'll use them via AJAX.
However, SOAP can be rather powerful with tons of standardized extensions that support enterprise features.
You could also use Hessian using HessianKit on the iPhone side, and HessianC# on the server side.
The big bonuses are:
1. Hessian in a binary serialization protocol, so smaller data payloads, good for 3G and GSM.
2. You do not need to worry about format in either end, transport is automated with proxies.
So on the server side you just define an C# interface, such as:
public interface IFruitService {
int FruitCount();
string GetFruit(int index);
}
Then you just subclass CHessianHandler and implement the IFruitService, and your web service is done.
On the iPhone just write the corresponding Objective-C protocol:
#protocol IFruitService
-(int)FruitCount;
-(NSString*)GetFruit:(int)index;
#end
That can then be access by proxy by a single line of code:
id<IFruitService> fruitService = [CWHessianConnection proxyWithURL:serviceURL
protocol:#protocol(IFruitService)];
Links:
HessianKit : hessiankit
I would certainly go with JSON, as others already noted - it's faster and data size is smaller. You can also use a data modelling framework like JSONModel to validate the JSON structure, and to autoconvert JSON objects to Obj-C objects.
JSONModel also includes classes for networking and working with APIs - also includes json rpc methods.
Have a look at these links:
http://www.jsonmodel.com - the JSONModel framework
http://json-rpc.org - specification for JSON APIs implementation
http://www.charlesproxy.com - the best tool to debug JSON APIs
http://json-schema.org - tool to define validation schemas for JSON, useful along the way
Short example of using JSONModel:
http://www.touch-code-magazine.com/how-to-make-a-youtube-app-using-mgbox-and-jsonmodel/
Hope these are useful