Is there a special reason why it is not possible to convert from json to collections? I am using a bean that contains settes with collections as params and json-lib can only serialize from json to java when i change these sette params to a list (or a set).
After a first glance at the json-lib code located in JSONObject.toBean(JSONObject, JsonConfig) i would say that all that is needed for this feature is to change the following lines (code taken from json-lib 2.4):
<code>
if( value instanceof JSONArray ){
if( List.class.isAssignableFrom( pd.getPropertyType() ) ){
setProperty( bean, key, convertPropertyValueToCollection( key, value,
jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig );
}else if( Set.class.isAssignableFrom( pd.getPropertyType() ) ){
setProperty( bean, key, convertPropertyValueToCollection( key, value,
jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig );
}else{
setProperty( bean, key, convertPropertyValueToArray( key, value,
targetType, jsonConfig, classMap ), jsonConfig );
}
}
</code>
to
<code>
if( value instanceof JSONArray ){
if( Collection.class.isAssignableFrom( pd.getPropertyType() ) ){
setProperty( bean, key, convertPropertyValueToCollection( key, value,
jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig );
}else{
setProperty( bean, key, convertPropertyValueToArray( key, value,
targetType, jsonConfig, classMap ), jsonConfig );
}
}
</code>
Am I right or is there something that i did not recognize? I tried to serialize to a java collection with the code given above (and a change in the JSONArray.toCollection method) and for me it works without any problems.
The changed code in JSONArray.toCollection is:
<code>
if( collectionType.isInterface() ){
if( collectionType.equals( List.class ) ){
collection = new ArrayList();
}else if( collectionType.equals( Set.class ) ){
collection = new HashSet();
}else if( collectionType.equals( Collection.class ) ){
collection = new ArrayList();
}else{
throw new JSONException( "unknown interface: " + collectionType );
}
}else{
...
}
</code>
Regards,
Niko
After some additional testing of the solution presented above, i found out that the solution presented does not handle all cases.
E.g: When calling a setter which expects a SortedSet, the serialization will still fail.