Improvement of JSON to JAVA marshalling with JSON-RPC

During debugging one of my porjects I’ve spoted the following code in from JSON-RPC library:

public Object unmarshall(SerializerState state, Class clazz, Object o)
Method setMethod = (Method)bd.writableProps.get(field);
if(setMethod != null) {
    setMethod.invoke(instance, invokeArgs);

The class is responsible of transforming Json notation to your Java Bean. Looking at code I realised that when no setter is present for field(or you mistyped field name in JSON) nothing happens. Nothing is set on the Bean obviously and no exception is thrown! Is some situation it makes sence. Silently dropping of absent fields is nice feature when you write backward compatible code or similar. But in most cases you want to rise an exception when field name does not match to Java bean fields. So I suggest to modify this code like following:

while(i.hasNext()) {
    String field = (String);
    Method setMethod = (Method)bd.writableProps.get(field);
    if(setMethod != null) {
	try {
	    Class param[] = setMethod.getParameterTypes();
	    fieldVal = ser.unmarshall(state, param[0], jso.get(field));
	} catch (UnmarshallException e) {
	    throw new UnmarshallException("bean " + clazz.getName() + " on field "+ field +
					  " " + e.getMessage());
	    log.fine("invoking " + setMethod.getName() +
		     "(" + fieldVal + ")");
	invokeArgs[0] = fieldVal;
	try {
	    setMethod.invoke(instance, invokeArgs);
	} catch (Throwable e) {
	    if(e instanceof InvocationTargetException)
		e = ((InvocationTargetException)e).getTargetException();
	    throw new UnmarshallException("bean " + clazz.getName() + "can't invoke " +
				 setMethod.getName() + ": " + e.getMessage());
    	if( ! "javaClass".equals(field)){
 		throw new RuntimeException("Class "+clazz +" does not have setter for field " + field +"!");

The next step would be to introduce lenientMarshalling configuration parameter for JSON-RPC bridge that controll strictness of marshalling operations.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: