GWT - Serializing POST parameter in JSON before sending - java

I am trying to invoke a REST server from my GWT client. The server is not under my control and I am using GWT just for the client. The service expects to receive a JSON which is going to be deserialized with Jackson and mapped to a Java bean like this:
public DTO {
String username;
String password;
/*...*/
}
Therefore, on my GWT project I created this class:
import com.google.gwt.json.client.JSONObject;
import com.lh.clte.client.gui.util.CLTELabelProperties;
public class DTO extends JSONObject {
String username;
String password;
/*...*/
}
And I am trying to send a POST request this way:
DTO dto= new DTO();
dto.setUsername(username);
dto.setPassword(password);
RequestBuilder b = new RequestBuilder(RequestBuilder.POST, url);
b.setHeader("content-type", "application/x-www-form-urlencoded");
/***** ERROR *************/
String data = dto.toString(); // JSONObject.toString(), no ovveriding
/*************************/
b.setRequestData(data);
b.setCallback(new MyCallback<DTO>());
try {
b.send();
} catch (RequestException e) {
e.printStackTrace();
}
However, the toString method doesn't produce the expected JSON, but rather the string "{}". Where am I doing it wrong?
I also tried com.google.gwt.json.client.dev.JsonObject, but it doesn't change the outcome.

You have to stringify your JSO object before sending over the wire:
String data = JsonUtils.stringify(dto);
This function is available in 2.7.0-SNAPSHOT, for 2.6.1 you have to create your own JSNI method
String data = stringify(dto);
private native String stringfy(JavaScriptObject jso) /*-{
return JSON.stringify(obj);
}-*/;

JSONObject is a "map", it's not meant to be extended.
You could have your accessors store the value in an internal JSONObject rather than in fields, or you could use a JavaScriptObject with accessors written in JSNI and using JsonUtils for parsing and JSONObject for serialization (new JSONObject(myJso).toString(), pending GWT 2.7's JsonUtils.stringify), or you could use AutoBeans.
See also https://stackoverflow.com/a/10685489/116472 or How to genearte JSON on the client, among many others.

If your backend uses Jackson, you should give gwt-jackson a try.
You'll be able to use any DTO and even the server beans if you have access to the sources.
You declare your mapper like that :
public static interface DTOWriter extends ObjectWriter<DTO> {}
And then :
DTOWriter dtoWriter = GWT.create(DTOWriter.class);
String data = dtoWriter.write(dto);
BTW, shouldn't your Content-type header be application/json ?

An alternative approach will be to use RestyGWT (http://restygwt.fusesource.org/).
RestyGWT will take care of both serializing to/from JSON and also doing the POST request.
In your example, you will need a Class that defines which fields are serializable:
public class DTO {
#Json(name = "username") // 'username' will be the name of the parameter in the json object
private String username;
#Json(name = "password")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Then, you define the service by extending RestService
public interface DTORestService extends RestService {
/**
* Utility/Convenience class.
* Use DTORestService.App.getInstance() to access static instance of DTORestService
*/
public static class App {
private static DTORestService ourInstance = null;
public static DTORestService getInstance() {
if (ourInstance == null) {
Defaults.setServiceRoot(host); // the host from the 'url' you want the POST to be sent
ourInstance = (DTORestService) GWT.create(DTORestService.class);
}
return ourInstance;
}
}
#POST
#Path("/dto.json") // the path from the 'url' you want the POST to be sent
public void getDTO(DTO dto, // the json object you want to add to the post
MethodCallback<DTO> callback); // the method callback with any json result you will receive
}
Finally, you can call it by doing:
DTO dto = new DTO();
dto.setUsername(username);
dto.setPassword(password);
DTORestService.getInstance().getDTO(dto, new AMethodCallback<DTO>());
hope it helps

Related

Best practice to deserialize a JSON using Spring MVC

I'm developing a web application using Spring MVC; it works as follows:
a JSON request is created from a model object (a POJO)
it's sent to an external server that exposes some APIs
a JSON response is received by the controller
I need to figure out which is the best way to serialize and deserialize JSON in a Java web application. At first I was using Gson but then I began to wonder if it was the right choice.
Is it possible to serialize and deserialize JSON to/from model
object using #RestController annotation? How does it works? I only find examples of how to create a rest service, in this sense
What is the best practice in this case? RestController? Gson? Jackson? Other?
N.B. My JsonResponse object has a generic field because the responses are all the same except that for a value. An example:
AccountRequest.class
public class AccountRequest() {
private String jsonrpc;
private String method;
private Map<String, Object> params;
private int id;
//constructor, getters and setters
}
JsonResponse.class
public class JsonResponse<T> {
private String jsonrpc;
private T result;
private String id;
//constructor, getters and setters
}
LoginResult.class
public class LoginResult {
private String token;
private String product;
private String error;
private Date lastLoginDate;
//constructor, getters and setters
}
MyController.class
#Controller
public class LoginController {
String response;
[...]
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView doLogin(#ModelAttribute("user") User user) {
[...]
//???
[...]
}
}
I open connection, send request and save the response in response String in MyController class. User parameter is annotated with #ModelAttribute to retrive the User object created by the showLoginForm() method.
Using Gson I know how to serialize request from my model object:
AccountRequest accountRequest = new AccountRequest();
accountRequest.setJsonrpc("2.0");
accountRequest.setMethod("method");
accountRequest.setParams(params);
accountRequest.setId(1);
String gson = new Gson().toJson(accountRequest);
JSONObject accountRequestJson = new JSONObject(gson);
And how to deserialize response in my model object:
Type jsonType = new TypeToken<JsonResponse<LoginResult>>() {}.getType();
JsonResponse<LoginResult> jsonResponse = new Gson().fromJson(response, jsonType);
The response is now saved into jsonResponse object, and I can put it in my ModelAndView.
Now, how can I deserialize it in my model object using #RestController and Jackson? Can you confirm it's the better method to do that? Can you post an example?
I hope it's not a silly question.
Thanks in advance!

How to get JSON in Java REST / AngularJS frontend

Can someone please help me how to get a JSON String in a Webservice. I's sending JSON to my /api/register that looks like:
{"name":"MyName","surname":"MySurename","email":"mail#asd.de","street":"MyStreet","number":"3","zip":"12345","city":"myCity","pass":"myPassword"}
Here is my register.java file:
#Path("/register")
#Stateless
public class RegisterWS {
#EJB
UserBS userBS;
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void createUser(){
// code to get data from json
userBS.createUser(name, surename, email, adress, number, zip, city, password);
}
}
My AngularJS Controller and Service. The Data comes from a form, that is parsed to a JSON object.
app.service('RegisterService', function ($http) {
return {
registerUser : function(user) {
$http.post('http://localhost:8080/myApp/api/register')
.success(function (user) {
return user;
})
.error(function (data) {
// failed
});
}
}
});
app.controller('RegisterCtrl', function($scope, RegisterService) {
$scope.register = function(){
RegisterService.registerUser(angular.toJson($scope.user));
}
});
You should have a POJO, which maps to the received JSON object, for example a User class. In this case this would be a very simple Java Bean, with mostly String properties for each field in the JSON.
#XmlRootElement
public class User {
String name;
String surname;
String email;
String street;
Integer number;
String zip;
String city;
String pass;
}
Of course you would use private fields, with getters and setters, but I did not want to add clutter. By the way the #XmlRootElement is a JAXB annotation, and JAX-RS uses JAXB internally.
After you have this, you just need to change your method like this
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void createUser(User user) {
...
}
You should not need to change anything on the AngularJS side, as the default for the $http.post method is JSON communication.
For your Java code, you have to add a User POJO, I dont know if you will use some persistence API or not, so the user POJO must implement serializable to output user object as JSON.
Here's a an example of REST app with EJB ... : http://tomee.apache.org/examples-trunk/rest-on-ejb/README.html
For your client app, you need to specify the content type : "Content-Type" = "application/json"
See this questions: change Content-type to "application/json" POST method, RESTful API

How to parse JSON Response to POJO with AndroidAnnotations?

I'm using AndroidAnnotations to build a Rest for an Android Application.
On the Serverside im using PHP, which send a json looking like :
{"tag":"register","success":0,"error":2,"msg":"User already existed","body":[]}
I have two POJOS :
User.java:
public class User implements Serializable {
private String name;
private String email;
private String password;
//getter and setter Methods
}
Response.java:
public class RegistrationResponse implements Serializable {
private String tag;
private int success;
private int error;
private String msg;
private String body;
//getter and setter Methods
}
Rest Client:
#Rest(rootUrl = "http://my.domain.com", converters = {
MappingJacksonHttpMessageConverter.class,
StringHttpMessageConverter.class, GsonHttpMessageConverter.class }, interceptors = { MyInterceptor.class })
public interface RestClient extends RestClientErrorHandling {
#Post("/user/register/{name}/{email}/{pass}")
#Accept(MediaType.APPLICATION_JSON_VALUE)
Response sendUserRegistration(User user, String name, String email,
String pass);
RestTemplate getRestTemplate();
}
Activity.java:
//User and Response are POJOs
Response result = RestClient.sendUserRegistration(user,
user.getName(),user.getEmail(),user.getPassword());
But i got an Null Pointer Exception error on Activity.java. But if i change the return value of "sendUserRegistration" function to String all work. So my "Response" POJO seems not to be converted from AndroidAnnotations.
How can i convert the Rest Response to my "Response"-POJO using AndroidAnnotations?
You don't need to return the entire response object per rest call, just set the response to your custom object. Or you can also return a JsonObject also and use gson to convert it later on.
#Rest(rootUrl = "http://my.domain.com", converters = {
MappingJacksonHttpMessageConverter.class,
StringHttpMessageConverter.class, GsonHttpMessageConverter.class }, interceptors = { MyInterceptor.class })
public interface RestClient extends RestClientErrorHandling {
#Post("/user/register/{name}/{email}/{pass}")
#Accept(MediaType.APPLICATION_JSON_VALUE)
User sendUserRegistration(User user, String name, String email,
String pass);
RestTemplate getRestTemplate();
}
then just simply call
User newUser = RestClient.sendUserRegistration(user,
user.getName(),user.getEmail(),user.getPassword());
AA relies on Spring Android RestTemplate to make the rest call. And in order to build requests and handle responses this lib uses converters. And to know which converter the RestTemplate should use, it checks the content-type response header.
As MappingJacksonHttpMessageConverter and GsonHttpMessageConverter handles only http response with content-type=application/json and your result is converted to string, I'm pretty sure you forgot to set this header in your php server. So it send the default one (ie: text/plain) which is only handle by StringHttpMessageConverter.
Also, the body field is an object in your json example, but in your POJO you declared it as a String. So parsing will fail on this point.

Using Gson with Interface Types

I am working on some server code, where the client sends requests in form of JSON. My problem is, there are a number of possible requests, all varying in small implementation details.
I therefore thought to use a Request interface, defined as:
public interface Request {
Response process ( );
}
From there, I implemented the interface in a class named LoginRequest as shown:
public class LoginRequest implements Request {
private String type = "LOGIN";
private String username;
private String password;
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* This method is what actually runs the login process, returning an
* appropriate response depending on the outcome of the process.
*/
#Override
public Response process() {
// TODO: Authenticate the user - Does username/password combo exist
// TODO: If the user details are ok, create the Player and add to list of available players
// TODO: Return a response indicating success or failure of the authentication
return null;
}
#Override
public String toString() {
return "LoginRequest [type=" + type + ", username=" + username
+ ", password=" + password + "]";
}
}
To work with JSON, I created a GsonBuilder instance and registered an InstanceCreator as shown:
public class LoginRequestCreator implements InstanceCreator<LoginRequest> {
#Override
public LoginRequest createInstance(Type arg0) {
return new LoginRequest("username", "password");
}
}
which I then used as shown in the snippet below:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(LoginRequest.class, new LoginRequestCreator());
Gson parser = builder.create();
Request request = parser.fromJson(completeInput, LoginRequest.class);
System.out.println(request);
and I get the expected output.
The thing I wish to do is replace the line Request request = parser.fromJson(completeInput, LoginRequest.class); with something similar to Request request = parser.fromJson(completeInput, Request.class); but doing that will not work, since Request is an interface.
I want my Gson to return the appropriate type of request depending on the received JSON.
An example of the JSON I passed to the server is shown below:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
To reiterate, I am looking for a way to parse requests (In JSON) from clients and return objects of classes implementing the Request interface
Polymorphic mapping of the type described is not available in Gson without some level of custom coding. There is an extension type adapter available as an extra that provides a bulk of the functionality you are looking for, with the caveat that the polymorphic sub-types need to be declared to the adapter ahead of time. Here is an example of its use:
public interface Response {}
public interface Request {
public Response process();
}
public class LoginRequest implements Request {
private String userName;
private String password;
// Constructors, getters/setters, overrides
}
public class PingRequest implements Request {
private String host;
private Integer attempts;
// Constructors, getters/setters, overrides
}
public class RequestTest {
#Test
public void testPolymorphicSerializeDeserializeWithGSON() throws Exception {
final TypeToken<List<Request>> requestListTypeToken = new TypeToken<List<Request>>() {
};
final RuntimeTypeAdapterFactory<Request> typeFactory = RuntimeTypeAdapterFactory
.of(Request.class, "type")
.registerSubtype(LoginRequest.class)
.registerSubtype(PingRequest.class);
final Gson gson = new GsonBuilder().registerTypeAdapterFactory(
typeFactory).create();
final List<Request> requestList = Arrays.asList(new LoginRequest(
"bob.villa", "passw0rd"), new LoginRequest("nantucket.jones",
"crabdip"), new PingRequest("example.com", 5));
final String serialized = gson.toJson(requestList,
requestListTypeToken.getType());
System.out.println("Original List: " + requestList);
System.out.println("Serialized JSON: " + serialized);
final List<Request> deserializedRequestList = gson.fromJson(serialized,
requestListTypeToken.getType());
System.out.println("Deserialized list: " + deserializedRequestList);
}
}
Note that you don't actually need to define the type property on the individual Java objects - it exists only in the JSON.
Assuming that the different possible JSON requests you may have are not extremely different to each other, I suggest a different approach, simpler in my opinion.
Let's say that you have these 3 different JSON requests:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
////////////////////////////////
{
"type":"SOMEREQUEST",
"param1":"someValue",
"param2":"someValue"
}
////////////////////////////////
{
"type":"OTHERREQUEST",
"param3":"someValue"
}
Gson allows you to have a single class to wrap all the possible responses, like this:
public class Request {
#SerializedName("type")
private String type;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("param1")
private String param1;
#SerializedName("param2")
private String param2;
#SerializedName("param3")
private String param3;
//getters & setters
}
By using the annotation #SerializedName, when Gson try to parse the JSON request, it just look, for each named attribute in the class, if there's a field in the JSON request with the same name. If there's no such field, the attribute in the class is just set to null.
This way you can parse many different JSON responses using only your Request class, like this:
Gson gson = new Gson();
Request request = gson.fromJson(jsonString, Request.class);
Once you have your JSON request parsed into your class, you can transfer the data from the wrap class to a concrete XxxxRequest object, something like:
switch (request.getType()) {
case "LOGIN":
LoginRequest req = new LoginRequest(request.getUsername(), request.getPassword());
break;
case "SOMEREQUEST":
SomeRequest req = new SomeRequest(request.getParam1(), request.getParam2());
break;
case "OTHERREQUEST":
OtherRequest req = new OtherRequest(request.getParam3());
break;
}
Note that this approach gets a bit more tedious if you have many different JSON requests and those requests are very different to each other, but even so I think is a good and very simple approach...
Genson library provides support for polymorphic types by default. Here is how it would work:
// tell genson to enable polymorphic types support
Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
// json value will be {"#class":"mypackage.LoginRequest", ... other properties ...}
String json = genson.serialize(someRequest);
// the value of #class property will be used to detect that the concrete type is LoginRequest
Request request = genson.deserialize(json, Request.class);
You can also use aliases for your types.
// a better way to achieve the same thing would be to use an alias
// no need to use setWithClassMetadata(true) as when you add an alias Genson
// will automatically enable the class metadata mechanism
genson = new Genson.Builder().addAlias("loginRequest", LoginRequest.class).create();
// output is {"#class":"loginRequest", ... other properties ...}
genson.serialize(someRequest);
By default, GSON cannot differentiate classes serialized as JSON; in other words, you will need to explicitly tell the parser what class you are expecting.
A solution could be custom deserializing or using a type adapter, as described here.
I found this answer: https://stackoverflow.com/a/28830173 which solved my issue when using Calendar as the interface as the RunTimeType would be GregorianCalendar.
Have a utility method to create GSON for an interface of generic type.
// Utility method to register interface and its implementation to work with GSON
public static <T> Gson buildInterface(Class<T> interfaceType, List<Class<? extends T>> interfaceImplmentations) {
final RuntimeTypeAdapterFactory<T> typeFactory = RuntimeTypeAdapterFactory.of(interfaceType, "type");
for (Class<? extends T> implementation : interfaceImplmentations) {
typeFactory.registerSubtype(implementation);
}
final Gson gson = new GsonBuilder().registerTypeAdapterFactory(typeFactory).create();
return gson;
}
// Build Gson
List<Class<? extends Request>> customConfigs = new ArrayList<>();
customConfigs.add(LoginRequest.getClass());
customConfigs.add(SomeOtherRequest.getClass());
Gson gson = buildInterface(Request.class, customConfigs);
Use this gson to serialize or deserialize and this works.

No suitable HttpMessageConverter found when trying to execute restclient request

I'm trying to use Spring for Android rest client to send data with an http post , to avoid creating and parsing the json data.
From their manual they have the following method:
restTemplate.postForObject(url, m, String.class)
After the method is called I get the following exception:
No suitable HttpMessageConverter found when trying to execute restclient request
My activity code snippet is :
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Message m = new Message();
m.setLibrary("1");
m.setPassword("1395");
m.setUserName("1395");
String result = restTemplate.postForObject(url, m, String.class);
And the Message object is :
public class Message {
private String UserName, Password, Library;
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getLibrary() {
return Library;
}
public void setLibrary(String library) {
Library = library;
}
}
Why can't it convert the Message object to JSON ?
There could be a few different reasons why this can happen. In my case, i had the RestTemplate already wired in, but still got this error. Turns out, i had to add a dependency on "jackson-databind":
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
It looks like you have not added a Message-specific HttpMessageConverter. HttpMessageConverter is an interface. You need to create a class that implements HttpMessageConverter<Message> and add an instance of that class to the RestTemplate via restTemplate.getMessageConverters().add(new MyMessageConverter());
Your code looks fine in general. Maybe this is a version problem. Check whether you use Jackson 2, and if so, change the converter to MappingJackson2HttpMessageConverter.
No need for something like HttpMessageConverter<Message>.
On a side node:
Java convention is to use lower casing for variable names. So, it would be more readable for other Java developers to do:
private String library;
public void setLibrary(String library) {
this.library = library;
}

Categories