source: tapas/web/src/json/serializers/AbstractJsonSerializer.java @ 376

Last change on this file since 376 was 376, checked in by rboipsl, 12 years ago

Creation projet tapas

File size: 2.3 KB
Line 
1package json.serializers;
2
3import java.lang.reflect.Type;
4import java.util.Locale;
5
6import net.sf.json.JSON;
7import net.sf.json.JSONObject;
8import net.sf.json.JSONSerializer;
9import net.sf.json.JsonConfig;
10import net.sf.json.processors.JsonBeanProcessor;
11
12import org.hibernate.Hibernate;
13import org.springframework.context.ApplicationContext;
14import org.springframework.context.ApplicationContextAware;
15import org.springframework.context.i18n.LocaleContextHolder;
16
17public 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}
Note: See TracBrowser for help on using the repository browser.