If you have a serializable java object and want to ship it over to another server than you may want to consider using GSON/JSON. I ran into an issue where a complex serializable object would not convert to JSON using GSON.TOJSON method.
so, I used the old trick in the book. For the sake of discussion assume that "SomeObject" is the java object which needs to be shipped as JSON back and forth client/server
on the client side
Step 1. convert the java object to byte[] (serialization)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(SomeObjectTobeSerialized);
oos.close();
baos.toByteArray();
Step 2. use GSON.toJSON. This shall convert the byte[] to JSONArray.
JSONObject json = new JSONObject();
json.put("BODY", serializeObject(SomeObject)); // serializeObject is the method whose body is Step 1 above
Now, send the JSON over to server via any of your favorite mechanism.
one the server side
Step 1. read the JSON from the request (HttpServletReq) object
StringBuilder sb = new StringBuilder();
BufferedReader reader = req.getReader();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
sb.append(inputLine);
}
JSONObject jsonRequest = new JSONObject(sb.toString());
Step2. deserialize JSONArray sent over by client
JSONArray serializedObject = jsonRequest.get("BODY")
byte[] bytes = new byte[serializedObject.length()];
InputStream is = null;
ObjectInputStream ois = null;
SomeObject str = null;
try {
int read = 0;
while (read < bytes.length) {
bytes[read] = (byte)serializedObject.getInt(read);
read++;
}
is = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(is);
str= (SomeObject) ois.readObject();
So, you get "SomeObject" back deserialized and intact.
Wednesday, May 12, 2010
Subscribe to:
Posts (Atom)