1 | package json.serializers; |
---|
2 | |
---|
3 | import java.lang.reflect.Type; |
---|
4 | import java.util.Locale; |
---|
5 | |
---|
6 | import net.sf.json.JSON; |
---|
7 | import net.sf.json.JSONObject; |
---|
8 | import net.sf.json.JSONSerializer; |
---|
9 | import net.sf.json.JsonConfig; |
---|
10 | import net.sf.json.processors.JsonBeanProcessor; |
---|
11 | |
---|
12 | import org.hibernate.Hibernate; |
---|
13 | import org.springframework.context.ApplicationContext; |
---|
14 | import org.springframework.context.ApplicationContextAware; |
---|
15 | import org.springframework.context.i18n.LocaleContextHolder; |
---|
16 | |
---|
17 | public abstract class AbstractJsonSerializer<T> |
---|
18 | implements JsonBeanProcessor, ApplicationContextAware |
---|
19 | { |
---|
20 | public abstract JSONObject process( final T t, final JsonConfig jsonConfig ); |
---|
21 | |
---|
22 | public void setApplicationContext( final ApplicationContext applicationContext ){} |
---|
23 | |
---|
24 | public final JSONObject processBean( final Object o, final JsonConfig jsonConfig ) |
---|
25 | { |
---|
26 | //noinspection unchecked |
---|
27 | return process( (T) o, jsonConfig ); |
---|
28 | } |
---|
29 | |
---|
30 | protected void serialize( final JSONObject json, final String key, final Object value, final JsonConfig jsonConfig ) |
---|
31 | { |
---|
32 | if( value == null ) |
---|
33 | return; |
---|
34 | |
---|
35 | if( value instanceof String ) |
---|
36 | putString( json, key, (String) value ); |
---|
37 | else if( value instanceof Number || value instanceof Boolean ) |
---|
38 | json.put( key, value ); |
---|
39 | else if( value instanceof Class<?> ) |
---|
40 | json.put( key, ( (Class<?>) value ).getName() ); |
---|
41 | else if( value instanceof Type || value instanceof Enum<?> ) |
---|
42 | json.put( key, value.toString() ); |
---|
43 | else if( Hibernate.isInitialized( value ) ) |
---|
44 | json.put( key, JSONSerializer.toJSON( value, jsonConfig ) ); |
---|
45 | } |
---|
46 | |
---|
47 | /** |
---|
48 | * Strings vaguely looking like json are automatically evaluated and converted to a JSONObject. We dont want that. |
---|
49 | * E.g.: without this function, {lua: "{npc='toto'}"} is added as : {lua: {npc: "toto"}}. |
---|
50 | * <p/> |
---|
51 | * See: http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html |
---|
52 | * > Keys can be followed by = or => as well as by : |
---|
53 | */ |
---|
54 | private void putString( final JSONObject json, final String key, final String value ) |
---|
55 | { |
---|
56 | json.put( key, value ); |
---|
57 | if( json.get( key ) instanceof JSON ) |
---|
58 | json.put( key, '\'' + value + '\'' ); |
---|
59 | } |
---|
60 | |
---|
61 | protected final Locale getLocale() |
---|
62 | { |
---|
63 | return LocaleContextHolder.getLocale(); |
---|
64 | } |
---|
65 | } |
---|