Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.util.ajax;
 
 import java.util.Map;
 import java.util.Set;
 
Converts POJOs to JSON and vice versa. The key difference: - returns the actual object from Convertor.fromJSON (JSONObjectConverter returns a Map) - the getters/setters are resolved at initialization (JSONObjectConverter resolves it at runtime) - correctly sets the number fields
 
 public class JSONPojoConvertor implements JSON.Convertor
 {
     private static final Logger LOG = Log.getLogger(JSONPojoConvertor.class);
     public static final Object[] GETTER_ARG = new Object[]{}, NULL_ARG = new Object[]{null};
     private static final Map<Class<?>, NumberType__numberTypes = new HashMap<Class<?>, NumberType>();
     
     public static NumberType getNumberType(Class<?> clazz)
     {
         return .get(clazz);
     }
     
     protected boolean _fromJSON;
     protected Class<?> _pojoClass;
     protected Map<String,Method_getters = new HashMap<String,Method>();
     protected Map<String,Setter_setters = new HashMap<String,Setter>();
     protected Set<String_excluded;

    

Parameters:
pojoClass The class to convert
 
     public JSONPojoConvertor(Class<?> pojoClass)
     {
         this(pojoClass, (Set<String>)nulltrue);
     }

    

Parameters:
pojoClass The class to convert
excluded The fields to exclude
 
     public JSONPojoConvertor(Class<?> pojoClassString[] excluded)
     {
         this(pojoClassnew HashSet<String>(Arrays.asList(excluded)), true);
     }

    

Parameters:
pojoClass The class to convert
excluded The fields to exclude
 
     public JSONPojoConvertor(Class<?> pojoClassSet<Stringexcluded)
     {
         this(pojoClassexcludedtrue);
     }

    

Parameters:
pojoClass The class to convert
excluded The fields to exclude
fromJSON If true, add a class field to the JSON
 
     public JSONPojoConvertor(Class<?> pojoClassSet<Stringexcludedboolean fromJSON)
     {
          = pojoClass;
          = excluded;
          = fromJSON;
         init();
     }    

    

Parameters:
pojoClass The class to convert
fromJSON If true, add a class field to the JSON
    public JSONPojoConvertor(Class<?> pojoClassboolean fromJSON)
    {
        this(pojoClass, (Set<String>)nullfromJSON);
    }
    
    /* ------------------------------------------------------------ */
    protected void init()
    {
        Method[] methods = .getMethods();
        for (int i=0;i<methods.length;i++)
        {
            Method m=methods[i];
            if (!Modifier.isStatic(m.getModifiers()) && m.getDeclaringClass()!=Object.class)
            {
                String name=m.getName();
                switch(m.getParameterTypes().length)
                {
                    case 0:
                        
                        if(m.getReturnType()!=null)
                        {
                            if (name.startsWith("is") && name.length()>2)
                                name=name.substring(2,3).toLowerCase(.)+name.substring(3);
                            else if (name.startsWith("get") && name.length()>3)
                                name=name.substring(3,4).toLowerCase(.)+name.substring(4);
                            else 
                                break;
                            if(includeField(namem))
                                addGetter(namem);
                        }
                        break;
                    case 1:
                        if (name.startsWith("set") && name.length()>3)
                        {
                            name=name.substring(3,4).toLowerCase(.)+name.substring(4);
                            if(includeField(namem))
                                addSetter(namem);
                        }
                        break;                
                }
            }
        }
    }
    
    /* ------------------------------------------------------------ */
    protected void addGetter(String nameMethod method)
    {
        .put(namemethod);
    }
    
    /* ------------------------------------------------------------ */
    protected void addSetter(String nameMethod method)
    {
        .put(namenew Setter(namemethod));
    }
    
    /* ------------------------------------------------------------ */
    protected Setter getSetter(String name)
    {
        return .get(name);
    }
    /* ------------------------------------------------------------ */
    protected boolean includeField(String nameMethod m)
    {
        return ==null || !.contains(name);
    }
    
    /* ------------------------------------------------------------ */
    protected int getExcludedCount()
    {
        return ==null ? 0 : .size();
    }
    /* ------------------------------------------------------------ */
    public Object fromJSON(Map object)
    {        
        Object obj = null;
        try
        {
            obj = .newInstance();
        }
        catch(Exception e)
        {
            // TODO return Map instead?
            throw new RuntimeException(e);
        }
        
        setProps(objobject);
        return obj;
    }
    
    /* ------------------------------------------------------------ */
    public int setProps(Object objMap<?,?> props)
    {
        int count = 0;
        for(Iterator<?> iterator = props.entrySet().iterator(); iterator.hasNext();)
        {
            Map.Entry<?, ?> entry = (Map.Entry<?,?>) iterator.next();
            Setter setter = getSetter((String)entry.getKey());
            if(setter!=null)
            {
                try
                {
                    setter.invoke(objentry.getValue());                    
                    count++;
                }
                catch(Exception e)
                {
                    // TODO throw exception?
                    .warn(.getName()+"#"+setter.getPropertyName()+" not set from "+
                            (entry.getValue().getClass().getName())+"="+entry.getValue().toString());
                    log(e);
                }
            }
        }
        return count;
    }
    /* ------------------------------------------------------------ */
    public void toJSON(Object objOutput out)
    {
        if()
            out.addClass();
        for(Map.Entry<String,Methodentry : .entrySet())
        {            
            try
            {
                out.add(entry.getKey(), entry.getValue().invoke(obj));                    
            }
            catch(Exception e)
            {
                // TODO throw exception?
                .warn("{} property '{}' excluded. (errors)".getName(), 
                        entry.getKey());
                log(e);
            }
        }        
    }
    
    /* ------------------------------------------------------------ */
    protected void log(Throwable t)
    {
        .ignore(t);
    }
    /* ------------------------------------------------------------ */
    public static class Setter
    {
        protected String _propertyName;
        protected Method _setter;
        protected NumberType _numberType;
        protected Class<?> _type;
        protected Class<?> _componentType;
        
        public Setter(String propertyNameMethod method)
        {
             = propertyName;
             = method;
             = method.getParameterTypes()[0];
             = .get();
            if(==null && .isArray())
            {
                 = .getComponentType();
                 = .get();
            }
        }
        
        public String getPropertyName()
        {
            return ;
        }
        
        public Method getMethod()
        {
            return ;
        }
        
        public NumberType getNumberType()
        {
            return ;
        }
        
        public Class<?> getType()
        {
            return ;
        }
        
        public Class<?> getComponentType()
        {
            return ;
        }
        
        public boolean isPropertyNumber()
        {
            return !=null;
        }
        
        public void invoke(Object objObject valuethrows IllegalArgumentException
        {
            if(value==null)
                .invoke(obj);
            else
                invokeObject(objvalue);
        }
        
        protected void invokeObject(Object objObject valuethrows IllegalArgumentException
        {
            
            if (.isEnum())
            {
                if (value instanceof Enum)
                    .invoke(objnew Object[]{value});
                else
                    .invoke(objnew Object[]{Enum.valueOf((Class<? extends Enum>),value.toString())});
            }
            else if(!=null && value instanceof Number)
            {
                .invoke(objnew Object[]{.getActualValue((Number)value)});
            }
            else if (..equals() || Character.class.equals())
            {
                .invoke(objnew Object[]{String.valueOf(value).charAt(0)});
            }
            else if(!=null && value.getClass().isArray())
            {
                if(==null)
                {
                    int len = Array.getLength(value);
                    Object array = Array.newInstance(len);
                    try
                    {
                        System.arraycopy(value, 0, array, 0, len);
                    }
                    catch(Exception e)
                    {                        
                        // unusual array with multiple types
                        .ignore(e);
                        .invoke(objnew Object[]{value});
                        return;
                    }                    
                    .invoke(objnew Object[]{array});
                }
                else
                {
                    Object[] old = (Object[])value;
                    Object array = Array.newInstance(old.length);
                    try
                    {
                        for(int i=0; i<old.lengthi++)
                            Array.set(arrayi.getActualValue((Number)old[i]));
                    }
                    catch(Exception e)
                    {                        
                        // unusual array with multiple types
                        .ignore(e);
                        .invoke(objnew Object[]{value});
                        return;
                    }
                    .invoke(objnew Object[]{array});
                }
            }
            else
                .invoke(objnew Object[]{value});
        }
    }
    
    public interface NumberType
    {        
        public Object getActualValue(Number number);     
    }
    
    public static final NumberType SHORT = new NumberType()
    {
        public Object getActualValue(Number number)
        {            
            return new Short(number.shortValue());
        } 
    };
    public static final NumberType INTEGER = new NumberType()
    {
        public Object getActualValue(Number number)
        {            
            return new Integer(number.intValue());
        }
    };
    
    public static final NumberType FLOAT = new NumberType()
    {
        public Object getActualValue(Number number)
        {            
            return new Float(number.floatValue());
        }      
    };
    public static final NumberType LONG = new NumberType()
    {
        public Object getActualValue(Number number)
        {            
            return number instanceof Long ? number : new Long(number.longValue());
        }     
    };
    public static final NumberType DOUBLE = new NumberType()
    {
        public Object getActualValue(Number number)
        {            
            return number instanceof Double ? number : new Double(number.doubleValue());
        }       
    };
    static
    {
        .put(Short.class);
        .put(.);
        .put(Integer.class);
        .put(Long.class);
        .put(.);
        .put(Float.class);
        .put(.);
        .put(Double.class);
        .put(.);
    }
New to GrepCode? Check out our FAQ X