1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.json.util;
18
19 import java.lang.reflect.Field;
20 import java.util.Map;
21
22 import net.sf.json.JSONException;
23 import net.sf.json.JsonConfig;
24
25 import org.apache.commons.beanutils.PropertyUtils;
26
27
28
29
30
31
32
33
34 public abstract class PropertySetStrategy {
35 public static final PropertySetStrategy DEFAULT = new DefaultPropertySetStrategy();
36
37 public abstract void setProperty( Object bean, String key, Object value ) throws JSONException;
38
39 public void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws JSONException {
40 setProperty( bean, key, value );
41 }
42
43 private static final class DefaultPropertySetStrategy extends PropertySetStrategy {
44 public void setProperty( Object bean, String key, Object value ) throws JSONException {
45 setProperty( bean, key, value, new JsonConfig());
46 }
47
48 public void setProperty( Object bean, String key, Object value, JsonConfig jsonConfig ) throws JSONException {
49 if( bean instanceof Map ){
50 ((Map) bean).put( key, value );
51 } else {
52 if( !jsonConfig.isIgnorePublicFields() ) {
53 try {
54 Field field = bean.getClass().getField( key );
55 if( field != null ) field.set( bean, value );
56 } catch( Exception e ){
57 _setProperty( bean, key, value );
58 }
59 } else {
60 _setProperty( bean, key, value );
61 }
62 }
63 }
64
65 private void _setProperty( Object bean, String key, Object value ) {
66 try {
67 PropertyUtils.setSimpleProperty( bean, key, value );
68 } catch( Exception e ) {
69 throw new JSONException( e );
70 }
71 }
72
73 }
74 }