GWT (Client) = How to convert Object to JSON and send to Server? - java

I know that GWT has a good RPC support. But for various purposes I need to build this on my own:
1.) How can I convert a Bean Object (on the Client Side) like;
class MyPerson {
String name;
String getName();
void setName(String name);
//..
}
with GWT into a JSON String? (Ideally only using libraries that come officially from GWT/Google).
2.) Secondly, how can I send this generated JSON String from the Client side to any Server also using any GWT Client Logik. (Ideally only using libraries that come officially from GWT/Google).
I have searched a lot, but the examples never show how to send data but only to receive JSON data.
Thank you very much!!!
Jens

There's a nifty class called AutoBeanFactory that GWT will create for you, no third-party libs required. See http://google-web-toolkit.googlecode.com/svn-history/r9219/javadoc/2.1/com/google/gwt/editor/client/AutoBeanFactory.html
Once you have your AutoBeanFactory, you can use it like this:
producing JSON from an object of type SimpleInterface
AutoBean<SimpleInterface> bean = beanFactory.create(SimpleInterface.class, simpleInterfaceInstance);
String requestData = AutoBeanCodex.encode(bean).getPayload();
useRequestBuilderToSendRequestWhereverYouWant(requestData);
parsing JSON from an object of type SimpleInterface
SimpleInterface simpleInterfaceInstance = AutoBeanCodex.decode(beanFactory, SimpleInterface.class, responseText).as();
You can use RequestBuilder to send these requests without GWT-RPC or the RF stuff.

I recommend you use RestyGWT it makes JSON rest services work just like GWT RPC services.

Take a look at GWT's AutoBean framework, which can be used to create and receive JSON payloads. The RequestBuilder type can be used to send HTTP requests to the server.

You have also another solution which is 3rd party solution, maybe a second place solution but it can be also the first place.
The 3rd party called GSON and it's a project open source on google code.
You can find it here.
I used it and it's very good and very simple.

Related

Read complete type structure while loading WSDL from Apache CXF using its internal class WSDLManager?

I'm trying to solve this interesting problem of converting all WSDL definitions to Open API/Swagger like API metadata. For this I zeroed on Apache CXF and found we have WSDLManager class implementation to parse WSDL files. I was able to get services, porttype, operations and messages. However, getting final message parameters and return types seems to be not straight forward.
Here is the snippet
public void parse(string wsdlPath){
Bus bus = BusFactory.getThreadDefaultBus();
WSDLManager man = bus.getExtension(WSDLManager.class);
Definition df = man.getDefinition(wsdlPath);
}
Any pointers will be greatly helpful.

Retrofit 2 without Model Class

i want to ask about Retrofit 2.0
all this time, i knew Retrofit only with GSON Converter and get the object.
But i dont know how to get the data with API like this
https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty
i'm trying to display all top stories and get the object after i load all the top stories first.
i only know with old school style like this: http://pastebin.com/JMpwjH8H
I'm pretty sure for your example you can just set the response type as a list of Integers like this:
public interface ApiInterface {
#GET("topstories.json?print=pretty")
Call<List<Integer>> getTopStories();
}
Using a POJO would be too complex for what is essentially, just an array of Integers.
First of all, you should know whether it is POST web service or GET web service.
what parameters you will be giving to get the desired response and how would you store the response in POJO. This tutorial will help you with all basic thing that you require for integrating web services

Use a shared JSON class on Server and Client

I want to create a shared class on GWT client and server which uses org.json.* on the server side and com.google.gwt.json.client.*on the client side.
My shared class is something like this:
import org.json.JSONObject;
class SomeDto {
public fromJSON (JSONObject x) }
}
}
This works fine on the server side but on the client side JSONObject should be replaced by com.google.gwt.json.client.JSONObject.
How can I use a shared JSON class on Server and Client, which uses different JSON implementations on client and server?
You have some implementations which work in client and server side:
Elemental Json is an entire implementation in java which works in server and client sides, take a look to its test cases to figure out how it works. It is very light weight and makes use of browser native optimisations in client side.
GwtQuery has a data binding implementation for json objects. It works in both sides and performs very well. Just define an interface extending JsonBuilder and you can share it in server and client. Take a look to this test class to see the usage or to its documentation. BTW gquery uses elemental json in order not to depend on the controversial json.org library.
Finally the classical AutoBeans in GWT is an option to handle JSON and bind it to POJOs. IMO it needs so much boiler-plate code.

Way to serialize a GWT client side object into a String and deserialize on the server?

Currently our application uses GWT-RPC for most client-server communication. Where this breaks down is when we need to auto generate images. We generate images based on dozens of parameters so what we do is build large complex urls and via a get request retrieve the dynamically built image.
If we could find a way to serialize Java objects in gwt client code and deserialize it on the server side we could make our urls much easier to work with. Instead of
http://host/page?param1=a&param2=b&param3=c....
we could have
http://host/page?object=?JSON/XML/Something Magicical
and on the server just have
new MagicDeserializer.(request.getParameter("object"),AwesomeClass.class);
I do not care what the intermediate format is json/xml/whatever I just really want to be able stop keeping track of manually marshalling/unmarshalling parameters in my gwt client code as well as servlets.
Use AutoBean Framework. What you need is simple and is all here http://code.google.com/p/google-web-toolkit/wiki/AutoBean
I've seen the most success and least amount of code using this library:
https://code.google.com/p/gwtprojsonserializer/
Along with the standard toString() you should have for all Object classes, I also have what's called a toJsonString() inside of each class I want "JSONable". Note, each class must extend JsonSerializable, which comes with the library:
public String toJsonString()
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return serializer.serializeToJson(this).toString();
}
To turn the JSON string back into an object, I put a static method inside of the same class, that recreates the class itself:
public static ClassName recreateClassViaJson(String json)
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return (ClassName) serializer.deSerialize(json, "full.package.name.ClassName");
}
Very simple!

How can I handle Java object serialization with JavaScript?

public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
private void calculate()
{
}
}
I have serialized the Java object located on the server side and sent it to the client
XStream xstream = new XStream(new DomDriver());
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
How can I deserialize that XML string into the Java object using JavaScript
and execute the methods of person class in the client side using the JavaScript?
Please help me with syntax or any guidelines.
You can call Java methods on the client side using JavaScript by using SOAP. This article explains how to create a WSDL web service that can be accessed by any SOAP client that supports WSDL.
You can then call the Java WSDL service using AJAX in JavaScript (if you can find a JS library that implements SOAP and WSDL).
Alternatively, you can write a simplified front-end to the Java WSDL service in PHP using PHP's built-in SoapClient library. Make it take some simple GET arguments and return JSON or XML. You could then trivially access the PHP web service using AJAX via jQuery (or an equivalent AJAX-supporting library).
If you're going for an applet and want to make Javascript calls from Java, checkout the LiveConnect with the JSObject wrapper class. This way you can excute javascript functions inside the applet (and pass information in between);
Executor exe = Executors.newSingleThreadExecutor();
final JSObject page = JSObject.getWindow(applet);
if (page == null) {
/* Break here, no connection could be made */
}
final String javascriptFunction = "yourJavaScriptFunction()";
executor.execute(new Runnable() {
public void run() {
page.eval(javascriptFunction);
}
});
Look into the IRIS applictation made for Flickr, it's open source and uses this technique. The Belgian JUG Parleys have a speech from a convention covering some of this, You can find it here.
XML is presented as a DOM tree to JavaScript
You can't run Java methods with Javascript. The only thing you could do is to read the properties of the Java object - this is the only information that is serialized in the XML file. It is very easy to read XML with javascript.
To be able to serialize a Java object, send it to a client and execute Java code there a totally different architecture would be needed. At first you need Java running on the client too. Then you would need to employ a method like RMI.

Categories

Resources