Introduction
When you're writing your own client and server protocol, you have to exchange data between them. There are many formats available (csv, xml, serialized objects...) and you can always define your own protocol.One format that has been getting more popular recently is JSON (JavaScript Object Notation, see http://en.wikipedia.org/wiki/JSON). It's a text format that allows objects to be serialized in a human-readable form. There's a library for Java called Json-lib ( http://json-lib.sourceforge.net/) that performs this serialization for you. This allows you to exchange JSON between your server and client without having to write any JSON code.
The Json-lib library
You can find some examples on how to use Json-lib here: http://json-lib.sourceforge.net/snippets.html. I use it like this:On the server (serialize to JSON):
1
2
3
|
User user = ...;
//get the user from database
String json = JSONObject.fromObject(user).toString();
//Send the json to the client
|
1
2
|
JSONObject jo = JSONObject.fromObject(response);
User user = (User) JSONObject.toBean(jo, User.
class
);
|
1
|
net.sf.json.JSONException: java.lang.NoSuchMethodException: Unknown property on
class
|
The solution
After searching for a way of telling Json-lib to ignore missing properties and not finding it, I decided the best approach would be to create my own PropertySetStrategy. A PropertySetStrategy defines how Json-lib sets the properties on your objects. The default strategy works pretty well, except that it throws an exception when a property is not found. So I decided to create a wrapper around this default PropertySetStrategy that ignores any exceptions happening when setting a property.This is my PropertySetStrategyWrapper:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import
net.sf.json.JSONException;
import
net.sf.json.util.PropertySetStrategy;
public
class
PropertyStrategyWrapper
extends
PropertySetStrategy {
private
PropertySetStrategy original;
public
PropertyStrategyWrapper(PropertySetStrategy original) {
this
.original = original;
}
@Override
public
void
setProperty(Object o, String string, Object o1)
throws
JSONException {
try
{
original.setProperty(o, string, o1);
}
catch
(Exception ex) {
//ignore
}
}
}
|
Now all we need to do is tell Json-lib to use our wrapper. Our client code now looks like this:
1
2
3
4
5
|
JSONObject jo = JSONObject.fromObject(response);
JsonConfig cfg =
new
JsonConfig();
cfg.setPropertySetStrategy(
new
PropertyStrategyWrapper(PropertySetStrategy.DEFAULT));
cfg.setRootClass(User.
class
);
User user = (User) JSONObject.toBean(jo, cfg);
|