throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");

前端之家收集整理的这篇文章主要介绍了throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

JSONObject.get*** null的话回报JSONException,大家注意下,附以下源码,正常try catch处理即可!!

@H_301_3@

package net.sf.json;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sf.ezmorph.Morpher;
import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.array.ObjectArrayMorpher;
import net.sf.ezmorph.bean.BeanMorpher;
import net.sf.ezmorph.object.IdentityObjectMorpher;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.processors.JsonBeanProcessor;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.processors.JsonVerifier;
import net.sf.json.processors.PropertyNameProcessor;
import net.sf.json.regexp.RegexpMatcher;
import net.sf.json.regexp.RegexpUtils;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.EnumMorpher;
import net.sf.json.util.JSONTokener;
import net.sf.json.util.JSONUtils;
import net.sf.json.util.NewBeanInstanceStrategy;
import net.sf.json.util.PropertyFilter;
import net.sf.json.util.PropertySetStrategy;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class JSONObject extends AbstractJSON
  implements JSON,Map,Comparable
{
  private static final Log log = LogFactory.getLog(JSONObject.class);
  private boolean nullObject;
  private Map properties;

  public static JSONObject fromObject(Object object)
  {
    return fromObject(object,new JsonConfig());
  }

  public static JSONObject fromObject(Object object,JsonConfig jsonConfig)
  {
    if ((object == null) || (JSONUtils.isNull(object)))
      return new JSONObject(true);
    if ((object instanceof Enum))
      throw new JSONException("'object' is an Enum. Use JSONArray instead");
    if (((object instanceof Annotation)) || ((object != null) && (object.getClass().isAnnotation())))
    {
      throw new JSONException("'object' is an Annotation.");
    }if ((object instanceof JSONObject))
      return _fromJSONObject((JSONObject)object,jsonConfig);
    if ((object instanceof DynaBean))
      return _fromDynaBean((DynaBean)object,jsonConfig);
    if ((object instanceof JSONTokener))
      return _fromJSONTokener((JSONTokener)object,jsonConfig);
    if ((object instanceof JSONString))
      return _fromJSONString((JSONString)object,jsonConfig);
    if ((object instanceof Map))
      return _fromMap((Map)object,jsonConfig);
    if ((object instanceof String))
      return _fromString((String)object,jsonConfig);
    if ((JSONUtils.isNumber(object)) || (JSONUtils.isBoolean(object)) || (JSONUtils.isString(object)))
    {
      return new JSONObject();
    }if (JSONUtils.isArray(object)) {
      throw new JSONException("'object' is an array. Use JSONArray instead");
    }
    return _fromBean(object,jsonConfig);
  }

  public static Object toBean(JSONObject jsonObject)
  {
    if ((jsonObject == null) || (jsonObject.isNullObject())) {
      return null;
    }

    DynaBean dynaBean = null;

    JsonConfig jsonConfig = new JsonConfig();
    Map props = JSONUtils.getProperties(jsonObject);
    dynaBean = JSONUtils.newDynaBean(jsonObject,jsonConfig);
    Iterator entries = jsonObject.names(jsonConfig).iterator();
    while (entries.hasNext()) {
      String name = (String)entries.next();
      String key = JSONUtils.convertToJavaIdentifier(name,jsonConfig);
      Class type = (Class)props.get(name);
      Object value = jsonObject.get(name);
      try {
        if (!JSONUtils.isNull(value)) {
          if ((value instanceof JSONArray))
            dynaBean.set(key,JSONArray.toCollection((JSONArray)value));
          else if ((String.class.isAssignableFrom(type)) || (Boolean.class.isAssignableFrom(type)) || (JSONUtils.isNumber(type)) || (Character.class.isAssignableFrom(type)) || (JSONFunction.class.isAssignableFrom(type)))
          {
            dynaBean.set(key,value);
          }
          else dynaBean.set(key,toBean((JSONObject)value));

        }
        else if (type.isPrimitive())
        {
          log.warn("Tried to assign null value to " + key + ":" + type.getName());
          dynaBean.set(key,JSONUtils.getMorpherRegistry().morph(type,null));
        }
        else {
          dynaBean.set(key,null);
        }
      }
      catch (JSONException jsone) {
        throw jsone;
      } catch (Exception e) {
        throw new JSONException("Error while setting property=" + name + " type" + type,e);
      }
    }

    return dynaBean;
  }

  public static Object toBean(JSONObject jsonObject,Class beanClass)
  {
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setRootClass(beanClass);
    return toBean(jsonObject,jsonConfig);
  }

  public static Object toBean(JSONObject jsonObject,Class beanClass,Map classMap)
  {
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setRootClass(beanClass);
    jsonConfig.setClassMap(classMap);
    return toBean(jsonObject,JsonConfig jsonConfig)
  {
    if ((jsonObject == null) || (jsonObject.isNullObject())) {
      return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
      return toBean(jsonObject);
    }
    if (classMap == null) {
      classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
      if (beanClass.isInterface()) {
        if (!Map.class.isAssignableFrom(beanClass)) {
          throw new JSONException("beanClass is an interface. " + beanClass);
        }
        bean = new HashMap();
      }
      else {
        bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass,jsonObject);
      }
    }
    catch (JSONException jsone) {
      throw jsone;
    } catch (Exception e) {
      throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    Iterator entries = jsonObject.names(jsonConfig).iterator();
    while (entries.hasNext()) {
      String name = (String)entries.next();
      Class type = (Class)props.get(name);
      Object value = jsonObject.get(name);
      if ((javaPropertyFilter != null) && (javaPropertyFilter.apply(bean,name,value))) {
        continue;
      }
      String key = (Map.class.isAssignableFrom(beanClass)) && (jsonConfig.isSkipJavaIdentifierTransformationInMapKeys()) ? name : JSONUtils.convertToJavaIdentifier(name,jsonConfig);

      PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
      if (propertyNameProcessor != null)
        key = propertyNameProcessor.processPropertyName(beanClass,key);
      try
      {
        if (Map.class.isAssignableFrom(beanClass))
        {
          if (JSONUtils.isNull(value)) {
            setProperty(bean,key,value,jsonConfig);
          } else if ((value instanceof JSONArray)) {
            setProperty(bean,convertPropertyValueToCollection(key,jsonConfig,classMap,List.class),jsonConfig);
          }
          else if ((String.class.isAssignableFrom(type)) || (JSONUtils.isBoolean(type)) || (JSONUtils.isNumber(type)) || (JSONUtils.isString(type)) || (JSONFunction.class.isAssignableFrom(type)))
          {
            if ((jsonConfig.isHandleJettisonEmptyElement()) && ("".equals(value)))
              setProperty(bean,null,jsonConfig);
            else
              setProperty(bean,jsonConfig);
          }
          else {
            Class targetClass = findTargetClass(key,classMap);
            targetClass = targetClass == null ? findTargetClass(name,classMap) : targetClass;

            JsonConfig jsc = jsonConfig.copy();
            jsc.setRootClass(targetClass);
            jsc.setClassMap(classMap);
            if (targetClass != null)
              setProperty(bean,toBean((JSONObject)value,jsc),toBean((JSONObject)value),jsonConfig);
          }
        }
        else {
          PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean,key);
          if ((pd != null) && (pd.getWriteMethod() == null)) {
            log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
            continue;
          }

          if (pd != null) {
            Class targetType = pd.getPropertyType();
            if (!JSONUtils.isNull(value)) {
              if ((value instanceof JSONArray)) {
                if (List.class.isAssignableFrom(pd.getPropertyType())) {
                  setProperty(bean,pd.getPropertyType()),jsonConfig);
                }
                else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                  setProperty(bean,jsonConfig);
                }
                else {
                  setProperty(bean,convertPropertyValueToArray(key,targetType,classMap),jsonConfig);
                }
              }
              else if ((String.class.isAssignableFrom(type)) || (JSONUtils.isBoolean(type)) || (JSONUtils.isNumber(type)) || (JSONUtils.isString(type)) || (JSONFunction.class.isAssignableFrom(type)))
              {
                if (pd != null) {
                  if ((jsonConfig.isHandleJettisonEmptyElement()) && ("".equals(value)))
                    setProperty(bean,jsonConfig);
                  else if (!targetType.isInstance(value)) {
                    setProperty(bean,morPHPropertyValue(key,type,targetType),jsonConfig);
                  }
                  else
                    setProperty(bean,jsonConfig);
                }
                else if ((beanClass == null) || ((bean instanceof Map)))
                  setProperty(bean,jsonConfig);
                else {
                  log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName());
                }

              }
              else if (jsonConfig.isHandleJettisonSingleElementArray()) {
                JSONArray array = new JSONArray().element(value,jsonConfig);
                Class newTargetClass = findTargetClass(key,classMap);
                newTargetClass = newTargetClass == null ? findTargetClass(name,classMap) : newTargetClass;

                JsonConfig jsc = jsonConfig.copy();
                jsc.setRootClass(newTargetClass);
                jsc.setClassMap(classMap);
                if (targetType.isArray()) {
                  setProperty(bean,JSONArray.toArray(array,jsonConfig);
                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                  setProperty(bean,array,jsonConfig);
                } else if ((List.class.isAssignableFrom(targetType)) || (Set.class.isAssignableFrom(targetType)))
                {
                  jsc.setCollectionType(targetType);
                  setProperty(bean,JSONArray.toCollection(array,jsonConfig);
                }
              } else {
                if ((targetType == Object.class) || (targetType.isInterface())) {
                  Class targetTypeCopy = targetType;
                  targetType = findTargetClass(key,classMap);
                  targetType = targetType == null ? findTargetClass(name,classMap) : targetType;

                  targetType = (targetType == null) && (targetTypeCopy.isInterface()) ? targetTypeCopy : targetType;
                }

                JsonConfig jsc = jsonConfig.copy();
                jsc.setRootClass(targetType);
                jsc.setClassMap(classMap);
                setProperty(bean,jsonConfig);
              }

            }
            else if (type.isPrimitive())
            {
              log.warn("Tried to assign null value to " + key + ":" + type.getName());
              setProperty(bean,null),jsonConfig);
            }
            else {
              setProperty(bean,jsonConfig);
            }

          }
          else if (!JSONUtils.isNull(value)) {
            if ((value instanceof JSONArray)) {
              setProperty(bean,jsonConfig);
            }
            else if ((String.class.isAssignableFrom(type)) || (JSONUtils.isBoolean(type)) || (JSONUtils.isNumber(type)) || (JSONUtils.isString(type)) || (JSONFunction.class.isAssignableFrom(type)))
            {
              if ((beanClass == null) || ((bean instanceof Map)) || (jsonConfig.getPropertySetStrategy() != null) || (!jsonConfig.isIgnorePublicFields()))
              {
                setProperty(bean,jsonConfig);
              }
              else log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName());

            }
            else if (jsonConfig.isHandleJettisonSingleElementArray()) {
              Class newTargetClass = findTargetClass(key,classMap);
              newTargetClass = newTargetClass == null ? findTargetClass(name,classMap) : newTargetClass;

              JsonConfig jsc = jsonConfig.copy();
              jsc.setRootClass(newTargetClass);
              jsc.setClassMap(classMap);
              setProperty(bean,jsonConfig);
            } else {
              setProperty(bean,jsonConfig);
            }

          }
          else if (type.isPrimitive())
          {
            log.warn("Tried to assign null value to " + key + ":" + type.getName());
            setProperty(bean,jsonConfig);
          }
          else {
            setProperty(bean,jsonConfig);
          }
        }
      }
      catch (JSONException jsone)
      {
        throw jsone;
      } catch (Exception e) {
        throw new JSONException("Error while setting property=" + name + " type " + type,e);
      }
    }

    return bean;
  }

  public static Object toBean(JSONObject jsonObject,Object root,JsonConfig jsonConfig)
  {
    if ((jsonObject == null) || (jsonObject.isNullObject()) || (root == null)) {
      return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
      throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
      classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    Iterator entries = jsonObject.names(jsonConfig).iterator();
    while (entries.hasNext()) {
      String name = (String)entries.next();
      Class type = (Class)props.get(name);
      Object value = jsonObject.get(name);
      if ((javaPropertyFilter != null) && (javaPropertyFilter.apply(root,value))) {
        continue;
      }
      String key = JSONUtils.convertToJavaIdentifier(name,jsonConfig);
      try {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root,key);
        if ((pd != null) && (pd.getWriteMethod() == null)) {
          log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED.");
          continue;
        }

        if (!JSONUtils.isNull(value)) {
          if ((value instanceof JSONArray)) {
            if ((pd == null) || (List.class.isAssignableFrom(pd.getPropertyType()))) {
              Class targetClass = findTargetClass(key,classMap);
              targetClass = targetClass == null ? findTargetClass(name,classMap) : targetClass;

              Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,null);

              List list = JSONArray.toList((JSONArray)value,newRoot,jsonConfig);
              setProperty(root,list,jsonConfig);
            } else {
              Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
              Class targetInnerType = findTargetClass(key,classMap);
              if ((innerType.equals(Object.class)) && (targetInnerType != null) && (!targetInnerType.equals(Object.class)))
              {
                innerType = targetInnerType;
              }
              Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType,null);

              Object array = JSONArray.toArray((JSONArray)value,jsonConfig);
              if ((innerType.isPrimitive()) || (JSONUtils.isNumber(innerType)) || (Boolean.class.isAssignableFrom(innerType)) || (JSONUtils.isString(innerType)))
              {
                array = JSONUtils.getMorpherRegistry().morph(Array.newInstance(innerType,0).getClass(),array);
              }
              else if (!array.getClass().equals(pd.getPropertyType()))
              {
                if (!pd.getPropertyType().equals(Object.class))
                {
                  Morpher morpher = JSONUtils.getMorpherRegistry().getMorpherFor(Array.newInstance(innerType,0).getClass());

                  if (IdentityObjectMorpher.getInstance().equals(morpher))
                  {
                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(new BeanMorpher(innerType,JSONUtils.getMorpherRegistry()));

                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                  }

                  array = JSONUtils.getMorpherRegistry().morph(Array.newInstance(innerType,array);
                }

              }

              setProperty(root,jsonConfig);
            }
          } else if ((String.class.isAssignableFrom(type)) || (JSONUtils.isBoolean(type)) || (JSONUtils.isNumber(type)) || (JSONUtils.isString(type)) || (JSONFunction.class.isAssignableFrom(type)))
          {
            if (pd != null) {
              if ((jsonConfig.isHandleJettisonEmptyElement()) && ("".equals(value))) {
                setProperty(root,jsonConfig);
              } else if (!pd.getPropertyType().isInstance(value))
              {
                Morpher morpher = JSONUtils.getMorpherRegistry().getMorpherFor(pd.getPropertyType());

                if (IdentityObjectMorpher.getInstance().equals(morpher))
                {
                  log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + pd.getPropertyType().getName() + ". Will register a default BeanMorpher");

                  JSONUtils.getMorpherRegistry().registerMorpher(new BeanMorpher(pd.getPropertyType(),JSONUtils.getMorpherRegistry()));
                }

                setProperty(root,JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(),value),jsonConfig);
              }
              else {
                setProperty(root,jsonConfig);
              }
            } else if ((root instanceof Map))
              setProperty(root,jsonConfig);
            else {
              log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + root.getClass().getName());
            }

          }
          else if (pd != null) {
            Class targetClass = pd.getPropertyType();
            if (jsonConfig.isHandleJettisonSingleElementArray()) {
              JSONArray array = new JSONArray().element(value,jsonConfig);
              Class newTargetClass = findTargetClass(key,classMap) : newTargetClass;

              Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,null);

              if (targetClass.isArray()) {
                setProperty(root,jsonConfig),jsonConfig);
              }
              else if (Collection.class.isAssignableFrom(targetClass)) {
                setProperty(root,JSONArray.toList(array,jsonConfig);
              }
              else if (JSONArray.class.isAssignableFrom(targetClass))
                setProperty(root,jsonConfig);
              else
                setProperty(root,jsonConfig);
            }
            else
            {
              if (targetClass == Object.class) {
                targetClass = findTargetClass(key,classMap);
                targetClass = targetClass == null ? findTargetClass(name,classMap) : targetClass;
              }

              Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,null);

              setProperty(root,jsonConfig);
            }
          }
          else if ((root instanceof Map)) {
            Class targetClass = findTargetClass(key,classMap) : targetClass;

            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,null);

            setProperty(root,jsonConfig);
          }
          else {
            log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + rootClass.getName());
          }

        }
        else if (type.isPrimitive())
        {
          log.warn("Tried to assign null value to " + key + ":" + type.getName());
          setProperty(root,jsonConfig);
        }
        else {
          setProperty(root,jsonConfig);
        }
      }
      catch (JSONException jsone) {
        throw jsone;
      } catch (Exception e) {
        throw new JSONException("Error while setting property=" + name + " type " + type,e);
      }
    }

    return root;
  }

  private static JSONObject _fromBean(Object bean,JsonConfig jsonConfig)
  {
    if (!addInstance(bean)) {
      try {
        return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(bean);
      }
      catch (JSONException jsone) {
        removeInstance(bean);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      } catch (RuntimeException e) {
        removeInstance(bean);
        JSONException jsone = new JSONException(e);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      }
    }
    fireObjectStartEvent(jsonConfig);

    JsonBeanProcessor processor = jsonConfig.findJsonBeanProcessor(bean.getClass());
    if (processor != null) {
      JSONObject json = null;
      try {
        json = processor.processBean(bean,jsonConfig);
        if (json == null) {
          json = (JSONObject)jsonConfig.findDefaultValueProcessor(bean.getClass()).getDefaultValue(bean.getClass());

          if (json == null) {
            json = new JSONObject(true);
          }
        }
        removeInstance(bean);
        fireObjectEndEvent(jsonConfig);
      } catch (JSONException jsone) {
        removeInstance(bean);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      }
      return json;
    }

    Class beanClass = bean.getClass();
    PropertyNameProcessor propertyNameProcessor = jsonConfig.findJsonPropertyNameProcessor(beanClass);
    Collection exclusions = jsonConfig.getMergedExcludes(beanClass);
    JSONObject jsonObject = new JSONObject();
    try {
      PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
      PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
      for (int i = 0; i < pds.length; i++) {
        boolean bypass = false;
        String key = pds[i].getName();
        if (exclusions.contains(key))
        {
          continue;
        }
        if ((jsonConfig.isIgnoreTransientFields()) && (isTransientField(key,beanClass,jsonConfig)))
        {
          continue;
        }
        Class type = pds[i].getPropertyType();
        try { pds[i].getReadMethod();
        } catch (Exception e)
        {
          String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED";
          fireWarnEvent(warning,jsonConfig);
          log.info(warning);
          continue;
        }
        if (pds[i].getReadMethod() != null)
        {
          if (isTransient(pds[i].getReadMethod(),jsonConfig))
            continue;
          Object value = PropertyUtils.getProperty(bean,key);
          if ((jsonPropertyFilter != null) && (jsonPropertyFilter.apply(bean,value))) {
            continue;
          }
          JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass,key);

          if (jsonValueProcessor != null) {
            value = jsonValueProcessor.processObjectValue(key,jsonConfig);
            bypass = true;
            if (!JsonVerifier.isValidJsonValue(value)) {
              throw new JSONException("Value is not a valid JSON value. " + value);
            }
          }
          if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass,key);
          }
          setValue(jsonObject,bypass);
        } else {
          String warning = "Property '" + key + "' of " + beanClass + " has no read method. SKIPPED";
          fireWarnEvent(warning,jsonConfig);
          log.info(warning);
        }
      }

      try
      {
        if (!jsonConfig.isIgnorePublicFields()) {
          Field[] fields = beanClass.getFields();
          for (int i = 0; i < fields.length; i++) {
            boolean bypass = false;
            Field field = fields[i];
            String key = field.getName();
            if (exclusions.contains(key))
            {
              continue;
            }
            if ((jsonConfig.isIgnoreTransientFields()) && (isTransient(field,jsonConfig)))
            {
              continue;
            }
            Class type = field.getType();
            Object value = field.get(bean);
            if ((jsonPropertyFilter != null) && (jsonPropertyFilter.apply(bean,value))) {
              continue;
            }
            JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClass,key);
            if (jsonValueProcessor != null) {
              value = jsonValueProcessor.processObjectValue(key,jsonConfig);
              bypass = true;
              if (!JsonVerifier.isValidJsonValue(value)) {
                throw new JSONException("Value is not a valid JSON value. " + value);
              }
            }
            if (propertyNameProcessor != null) {
              key = propertyNameProcessor.processPropertyName(beanClass,key);
            }
            setValue(jsonObject,bypass);
          }
        }
      }
      catch (Exception e) {
        log.trace("Couldn't read public fields.",e);
      }
    } catch (JSONException jsone) {
      removeInstance(bean);
      fireErrorEvent(jsone,jsonConfig);
      throw jsone;
    } catch (Exception e) {
      removeInstance(bean);
      JSONException jsone = new JSONException(e);
      fireErrorEvent(jsone,jsonConfig);
      throw jsone;
    }

    removeInstance(bean);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
  }

  private static JSONObject _fromDynaBean(DynaBean bean,JsonConfig jsonConfig) {
    if (bean == null) {
      fireObjectStartEvent(jsonConfig);
      fireObjectEndEvent(jsonConfig);
      return new JSONObject(true);
    }

    if (!addInstance(bean)) {
      try {
        return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(bean);
      }
      catch (JSONException jsone) {
        removeInstance(bean);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      }
    }
    fireObjectStartEvent(jsonConfig);

    JSONObject jsonObject = new JSONObject();
    try {
      DynaProperty[] props = bean.getDynaClass().getDynaProperties();

      Collection exclusions = jsonConfig.getMergedExcludes();
      PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
      for (int i = 0; i < props.length; i++) {
        boolean bypass = false;
        DynaProperty dynaProperty = props[i];
        String key = dynaProperty.getName();
        if (exclusions.contains(key)) {
          continue;
        }
        Class type = dynaProperty.getType();
        Object value = bean.get(dynaProperty.getName());
        if ((jsonPropertyFilter != null) && (jsonPropertyFilter.apply(bean,value))) {
          continue;
        }
        JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(type,key);
        if (jsonValueProcessor != null) {
          value = jsonValueProcessor.processObjectValue(key,jsonConfig);
          bypass = true;
          if (!JsonVerifier.isValidJsonValue(value)) {
            throw new JSONException("Value is not a valid JSON value. " + value);
          }
        }
        setValue(jsonObject,bypass);
      }
    } catch (JSONException jsone) {
      removeInstance(bean);
      fireErrorEvent(jsone,jsonConfig);
      throw jsone;
    } catch (RuntimeException e) {
      removeInstance(bean);
      JSONException jsone = new JSONException(e);
      fireErrorEvent(jsone,jsonConfig);
      throw jsone;
    }

    removeInstance(bean);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
  }

  private static JSONObject _fromJSONObject(JSONObject object,JsonConfig jsonConfig) {
    if ((object == null) || (object.isNullObject())) {
      fireObjectStartEvent(jsonConfig);
      fireObjectEndEvent(jsonConfig);
      return new JSONObject(true);
    }

    if (!addInstance(object)) {
      try {
        return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(object);
      }
      catch (JSONException jsone) {
        removeInstance(object);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      } catch (RuntimeException e) {
        removeInstance(object);
        JSONException jsone = new JSONException(e);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      }
    }
    fireObjectStartEvent(jsonConfig);

    JSONArray sa = object.names(jsonConfig);
    Collection exclusions = jsonConfig.getMergedExcludes();
    JSONObject jsonObject = new JSONObject();
    PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
    for (Iterator i = sa.iterator(); i.hasNext(); ) {
      Object k = i.next();
      if (k == null) {
        throw new JSONException("JSON keys cannot be null.");
      }
      if ((!(k instanceof String)) && (!jsonConfig.isAllowNonStringKeys())) {
        throw new ClassCastException("JSON keys must be strings.");
      }
      String key = String.valueOf(k);
      if ("null".equals(key)) {
        throw new NullPointerException("JSON keys must not be null nor the 'null' string.");
      }
      if (exclusions.contains(key)) {
        continue;
      }
      Object value = object.opt(key);
      if ((jsonPropertyFilter != null) && (jsonPropertyFilter.apply(object,value))) {
        continue;
      }
      if (jsonObject.properties.containsKey(key)) {
        jsonObject.accumulate(key,jsonConfig);
        firePropertySetEvent(key,true,jsonConfig);
      } else {
        jsonObject.setInternal(key,false,jsonConfig);
      }
    }

    removeInstance(object);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
  }

  private static JSONObject _fromJSONString(JSONString string,JsonConfig jsonConfig) {
    return _fromJSONTokener(new JSONTokener(string.toJSONString()),jsonConfig);
  }

  private static JSONObject _fromJSONTokener(JSONTokener tokener,JsonConfig jsonConfig)
  {
    try
    {
      if (tokener.matches("null.*")) {
        fireObjectStartEvent(jsonConfig);
        fireObjectEndEvent(jsonConfig);
        return new JSONObject(true);
      }

      if (tokener.nextClean() != '{') {
        throw tokener.SyntaxError("A JSONObject text must begin with '{'");
      }
      fireObjectStartEvent(jsonConfig);

      Collection exclusions = jsonConfig.getMergedExcludes();
      PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
      JSONObject jsonObject = new JSONObject();
      while (true) {
        char c = tokener.nextClean();
        switch (c) {
        case '\000':
          throw tokener.SyntaxError("A JSONObject text must end with '}'");
        case '}':
          fireObjectEndEvent(jsonConfig);
          return jsonObject;
        }
        tokener.back();
        String key = tokener.nextValue(jsonConfig).toString();

        c = tokener.nextClean();
        if (c == '=') {
          if (tokener.next() != '>')
            tokener.back();
        }
        else if (c != ':') {
          throw tokener.SyntaxError("Expected a ':' after a key");
        }

        char peek = tokener.peek();
        boolean quoted = (peek == '"') || (peek == '\'');
        Object v = tokener.nextValue(jsonConfig);
        if ((quoted) || (!JSONUtils.isFunctionHeader(v))) {
          if (exclusions.contains(key)) {
            switch (tokener.nextClean()) {
            case ',':
            case ';':
              if (tokener.nextClean() == '}') {
                fireObjectEndEvent(jsonConfig);
                return jsonObject;
              }
              tokener.back();
              break;
            case '}':
              fireObjectEndEvent(jsonConfig);
              return jsonObject;
            default:
              throw tokener.SyntaxError("Expected a ',' or '}'");
            }
          }

          if ((jsonPropertyFilter == null) || (!jsonPropertyFilter.apply(tokener,v))) {
            if ((quoted) && ((v instanceof String)) && ((JSONUtils.mayBeJSON((String)v)) || (JSONUtils.isFunction(v)))) {
              v = "\"" + v + "\"";
            }
            if (jsonObject.properties.containsKey(key)) {
              jsonObject.accumulate(key,v,jsonConfig);
              firePropertySetEvent(key,jsonConfig);
            } else {
              jsonObject.element(key,jsonConfig);
            }
          }
        }
        else {
          String params = JSONUtils.getFunctionParams((String)v);

          int i = 0;
          StringBuffer sb = new StringBuffer();
          while (true) {
            char ch = tokener.next();
            if (ch == 0) {
              break;
            }
            if (ch == '{') {
              i++;
            }
            if (ch == '}') {
              i--;
            }
            sb.append(ch);
            if (i == 0) {
              break;
            }
          }
          if (i != 0) {
            throw tokener.SyntaxError("Unbalanced '{' or '}' on prop: " + v);
          }

          String text = sb.toString();
          text = text.substring(1,text.length() - 1).trim();

          Object value = new JSONFunction(params != null ? StringUtils.split(params,",") : null,text);

          if ((jsonPropertyFilter == null) || (!jsonPropertyFilter.apply(tokener,value))) {
            if (jsonObject.properties.containsKey(key)) {
              jsonObject.accumulate(key,jsonConfig);
            }

          }

        }

        switch (tokener.nextClean()) {
        case ',':
        case ';':
          if (tokener.nextClean() == '}') {
            fireObjectEndEvent(jsonConfig);
            return jsonObject;
          }
          tokener.back();
          break;
        case '}':
          fireObjectEndEvent(jsonConfig);
          return jsonObject;
        default:
          throw tokener.SyntaxError("Expected a ',' or '}'");
        }
      }
    } catch (JSONException jsone) {
      fireErrorEvent(jsone,jsonConfig);
    }throw jsone;
  }

  private static JSONObject _fromMap(Map map,JsonConfig jsonConfig)
  {
    if (map == null) {
      fireObjectStartEvent(jsonConfig);
      fireObjectEndEvent(jsonConfig);
      return new JSONObject(true);
    }

    if (!addInstance(map)) {
      try {
        return jsonConfig.getCycleDetectionStrategy().handleRepeatedReferenceAsObject(map);
      }
      catch (JSONException jsone) {
        removeInstance(map);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      } catch (RuntimeException e) {
        removeInstance(map);
        JSONException jsone = new JSONException(e);
        fireErrorEvent(jsone,jsonConfig);
        throw jsone;
      }
    }
    fireObjectStartEvent(jsonConfig);

    Collection exclusions = jsonConfig.getMergedExcludes();
    JSONObject jsonObject = new JSONObject();
    PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
    try {
      Iterator entries = map.entrySet().iterator();
      while (entries.hasNext()) {
        boolean bypass = false;
        Map.Entry entry = (Map.Entry)entries.next();
        Object k = entry.getKey();
        if (k == null) {
          throw new JSONException("JSON keys cannot be null.");
        }
        if ((!(k instanceof String)) && (!jsonConfig.isAllowNonStringKeys())) {
          throw new ClassCastException("JSON keys must be strings.");
        }
        String key = String.valueOf(k);
        if ("null".equals(key)) {
          throw new NullPointerException("JSON keys must not be null nor the 'null' string.");
        }
        if (exclusions.contains(key)) {
          continue;
        }
        Object value = entry.getValue();
        if ((jsonPropertyFilter != null) && (jsonPropertyFilter.apply(map,value))) {
          continue;
        }
        if (value != null) {
          JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(value.getClass(),jsonConfig);
            bypass = true;
            if (!JsonVerifier.isValidJsonValue(value)) {
              throw new JSONException("Value is not a valid JSON value. " + value);
            }
          }
          setValue(jsonObject,value.getClass(),bypass);
        }
        else if (jsonObject.properties.containsKey(key)) {
          jsonObject.accumulate(key,JSONNull.getInstance());
          firePropertySetEvent(key,JSONNull.getInstance(),jsonConfig);
        } else {
          jsonObject.element(key,jsonConfig);
        }
      }
    }
    catch (JSONException jsone) {
      removeInstance(map);
      fireErrorEvent(jsone,jsonConfig);
      throw jsone;
    } catch (RuntimeException e) {
      removeInstance(map);
      JSONException jsone = new JSONException(e);
      fireErrorEvent(jsone,jsonConfig);
      throw jsone;
    }

    removeInstance(map);
    fireObjectEndEvent(jsonConfig);
    return jsonObject;
  }

  private static JSONObject _fromString(String str,JsonConfig jsonConfig) {
    if ((str == null) || ("null".equals(str))) {
      fireObjectStartEvent(jsonConfig);
      fireObjectEndEvent(jsonConfig);
      return new JSONObject(true);
    }
    return _fromJSONTokener(new JSONTokener(str),jsonConfig);
  }

  private static Object convertPropertyValueToArray(String key,Object value,Class targetType,JsonConfig jsonConfig,Map classMap)
  {
    Class innerType = JSONUtils.getInnerComponentType(targetType);
    Class targetInnerType = findTargetClass(key,classMap);
    if ((innerType.equals(Object.class)) && (targetInnerType != null) && (!targetInnerType.equals(Object.class)))
    {
      innerType = targetInnerType;
    }
    JsonConfig jsc = jsonConfig.copy();
    jsc.setRootClass(innerType);
    jsc.setClassMap(classMap);
    Object array = JSONArray.toArray((JSONArray)value,jsc);
    if ((innerType.isPrimitive()) || (JSONUtils.isNumber(innerType)) || (Boolean.class.isAssignableFrom(innerType)) || (JSONUtils.isString(innerType)))
    {
      array = JSONUtils.getMorpherRegistry().morph(Array.newInstance(innerType,array);
    }
    else if (!array.getClass().equals(targetType))
    {
      if (!targetType.equals(Object.class)) {
        Morpher morpher = JSONUtils.getMorpherRegistry().getMorpherFor(Array.newInstance(innerType,0).getClass());

        if (IdentityObjectMorpher.getInstance().equals(morpher))
        {
          ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(new BeanMorpher(innerType,JSONUtils.getMorpherRegistry()));

          JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
        }

        array = JSONUtils.getMorpherRegistry().morph(Array.newInstance(innerType,array);
      }

    }

    return array;
  }

  private static List convertPropertyValueToList(String key,String name,Map classMap)
  {
    Class targetClass = findTargetClass(key,classMap);
    targetClass = targetClass == null ? findTargetClass(name,classMap) : targetClass;
    JsonConfig jsc = jsonConfig.copy();
    jsc.setRootClass(targetClass);
    jsc.setClassMap(classMap);
    List list = (List)JSONArray.toCollection((JSONArray)value,jsc);
    return list;
  }

  private static Collection convertPropertyValueToCollection(String key,Map classMap,Class collectionType)
  {
    Class targetClass = findTargetClass(key,classMap) : targetClass;
    JsonConfig jsc = jsonConfig.copy();
    jsc.setRootClass(targetClass);
    jsc.setClassMap(classMap);
    jsc.setCollectionType(collectionType);
    return JSONArray.toCollection((JSONArray)value,jsc);
  }

  private static Class findTargetClass(String key,Map classMap)
  {
    Class targetClass = (Class)classMap.get(key);
    if (targetClass == null)
    {
      Iterator i = classMap.entrySet().iterator();
      while (i.hasNext()) {
        Map.Entry entry = (Map.Entry)i.next();
        if (RegexpUtils.getMatcher((String)entry.getKey()).matches(key))
        {
          targetClass = (Class)entry.getValue();
          break;
        }
      }
    }

    return targetClass;
  }

  private static boolean isTransientField(String name,JsonConfig jsonConfig) {
    try {
      Field field = beanClass.getDeclaredField(name);
      if ((field.getModifiers() & 0x80) == 128) return true;
      return isTransient(field,jsonConfig);
    } catch (Exception e) {
      log.info("Error while inspecting field " + beanClass + "." + name + " for transient status.",e);
    }
    return false;
  }

  private static boolean isTransient(AnnotatedElement element,JsonConfig jsonConfig) {
    for (Iterator annotations = jsonConfig.getIgnoreFieldAnnotations().iterator(); annotations.hasNext(); ) {
      try {
        String annotationClassName = (String)annotations.next();
        if (element.getAnnotation(Class.forName(annotationClassName)) != null) return true; 
      }
      catch (Exception e) {
        log.info("Error while inspecting " + element + " for transient status.",e);
      }
    }
    return false;
  }

  private static Object morPHPropertyValue(String key,Class type,Class targetType) {
    Morpher morpher = JSONUtils.getMorpherRegistry().getMorpherFor(targetType);

    if (IdentityObjectMorpher.getInstance().equals(morpher))
    {
      log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + targetType.getName() + ". Will register a default Morpher");

      if (Enum.class.isAssignableFrom(targetType)) {
        JSONUtils.getMorpherRegistry().registerMorpher(new EnumMorpher(targetType));
      }
      else {
        JSONUtils.getMorpherRegistry().registerMorpher(new BeanMorpher(targetType,JSONUtils.getMorpherRegistry()));
      }

    }

    value = JSONUtils.getMorpherRegistry().morph(targetType,value);

    return value;
  }

  private static void setProperty(Object bean,String key,JsonConfig jsonConfig)
    throws Exception
  {
    PropertySetStrategy propertySetStrategy = jsonConfig.getPropertySetStrategy() != null ? jsonConfig.getPropertySetStrategy() : PropertySetStrategy.DEFAULT;

    propertySetStrategy.setProperty(bean,jsonConfig);
  }

  private static void setValue(JSONObject jsonObject,boolean bypass)
  {
    boolean accumulated = false;
    if (value == null) {
      value = jsonConfig.findDefaultValueProcessor(type).getDefaultValue(type);

      if (!JsonVerifier.isValidJsonValue(value)) {
        throw new JSONException("Value is not a valid JSON value. " + value);
      }
    }
    if (jsonObject.properties.containsKey(key)) {
      if (String.class.isAssignableFrom(type)) {
        Object o = jsonObject.opt(key);
        if ((o instanceof JSONArray))
          ((JSONArray)o).addString((String)value);
        else
          jsonObject.properties.put(key,new JSONArray().element(o).addString((String)value));
      }
      else
      {
        jsonObject.accumulate(key,jsonConfig);
      }
      accumulated = true;
    }
    else if ((bypass) || (String.class.isAssignableFrom(type))) {
      jsonObject.properties.put(key,value);
    } else {
      jsonObject.setInternal(key,jsonConfig);
    }

    value = jsonObject.opt(key);
    if (accumulated) {
      JSONArray array = (JSONArray)value;
      value = array.get(array.size() - 1);
    }
    firePropertySetEvent(key,accumulated,jsonConfig);
  }

  public JSONObject()
  {
    this.properties = new ListOrderedMap();
  }

  public JSONObject(boolean isNull)
  {
    this();
    this.nullObject = isNull;
  }

  public JSONObject accumulate(String key,boolean value)
  {
    return _accumulate(key,value ? Boolean.TRUE : Boolean.FALSE,new JsonConfig());
  }

  public JSONObject accumulate(String key,double value)
  {
    return _accumulate(key,Double.valueOf(value),int value)
  {
    return _accumulate(key,Integer.valueOf(value),long value)
  {
    return _accumulate(key,Long.valueOf(value),Object value)
  {
    return _accumulate(key,JsonConfig jsonConfig)
  {
    return _accumulate(key,jsonConfig);
  }

  public void accumulateAll(Map map) {
    accumulateAll(map,new JsonConfig());
  }

  public void accumulateAll(Map map,JsonConfig jsonConfig) {
    if ((map instanceof JSONObject)) {
      Iterator entries = map.entrySet().iterator();
      while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry)entries.next();
        String key = (String)entry.getKey();
        Object value = entry.getValue();
        accumulate(key,jsonConfig);
      }
    } else {
      Iterator entries = map.entrySet().iterator();
      while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry)entries.next();
        String key = String.valueOf(entry.getKey());
        Object value = entry.getValue();
        accumulate(key,jsonConfig);
      }
    }
  }

  public void clear() {
    this.properties.clear();
  }

  public int compareTo(Object obj) {
    if ((obj != null) && ((obj instanceof JSONObject))) {
      JSONObject other = (JSONObject)obj;
      int size1 = size();
      int size2 = other.size();
      if (size1 < size2)
        return -1;
      if (size1 > size2)
        return 1;
      if (equals(other)) {
        return 0;
      }
    }
    return -1;
  }

  public boolean containsKey(Object key) {
    return this.properties.containsKey(key);
  }

  public boolean containsValue(Object value) {
    return containsValue(value,new JsonConfig());
  }

  public boolean containsValue(Object value,JsonConfig jsonConfig) {
    try {
      value = processValue(value,jsonConfig);
    } catch (JSONException e) {
      return false;
    }
    return this.properties.containsValue(value);
  }

  public JSONObject discard(String key)
  {
    verifyIsNull();
    this.properties.remove(key);
    return this;
  }

  public JSONObject element(String key,boolean value)
  {
    verifyIsNull();
    return element(key,value ? Boolean.TRUE : Boolean.FALSE);
  }

  public JSONObject element(String key,Collection value)
  {
    return element(key,new JsonConfig());
  }

  public JSONObject element(String key,Collection value,JsonConfig jsonConfig)
  {
    if (!(value instanceof JSONArray)) {
      value = JSONArray.fromObject(value,jsonConfig);
    }
    return setInternal(key,jsonConfig);
  }

  public JSONObject element(String key,double value)
  {
    verifyIsNull();
    Double d = new Double(value);
    JSONUtils.testValidity(d);
    return element(key,d);
  }

  public JSONObject element(String key,int value)
  {
    verifyIsNull();
    return element(key,new Integer(value));
  }

  public JSONObject element(String key,long value)
  {
    verifyIsNull();
    return element(key,new Long(value));
  }

  public JSONObject element(String key,Map value)
  {
    return element(key,Map value,JsonConfig jsonConfig)
  {
    verifyIsNull();
    if ((value instanceof JSONObject)) {
      return setInternal(key,jsonConfig);
    }
    return element(key,fromObject(value,Object value)
  {
    return element(key,JsonConfig jsonConfig)
  {
    verifyIsNull();
    if (key == null) {
      throw new JSONException("Null key.");
    }
    if (value != null) {
      value = processValue(key,jsonConfig);
      _setInternal(key,jsonConfig);
    } else {
      remove(key);
    }
    return this;
  }

  public JSONObject elementOpt(String key,Object value)
  {
    return elementOpt(key,new JsonConfig());
  }

  public JSONObject elementOpt(String key,JsonConfig jsonConfig)
  {
    verifyIsNull();
    if ((key != null) && (value != null)) {
      element(key,jsonConfig);
    }
    return this;
  }

  public Set entrySet() {
    return Collections.unmodifiableSet(this.properties.entrySet());
  }

  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj == null) {
      return false;
    }

    if (!(obj instanceof JSONObject)) {
      return false;
    }

    JSONObject other = (JSONObject)obj;

    if (isNullObject())
    {
      return other.isNullObject();
    }

    if (other.isNullObject()) {
      return false;
    }

    if (other.size() != size()) {
      return false;
    }

    Iterator keys = this.properties.keySet().iterator();
    while (keys.hasNext()) {
      String key = (String)keys.next();
      if (!other.properties.containsKey(key)) {
        return false;
      }
      Object o1 = this.properties.get(key);
      Object o2 = other.properties.get(key);

      if (JSONNull.getInstance().equals(o1))
      {
        if (!JSONNull.getInstance().equals(o2))
        {
          return false;
        }
      }
      if (JSONNull.getInstance().equals(o2))
      {
        return false;
      }

      if (((o1 instanceof String)) && ((o2 instanceof JSONFunction))) {
        if (!o1.equals(String.valueOf(o2)))
          return false;
      }
      else if (((o1 instanceof JSONFunction)) && ((o2 instanceof String))) {
        if (!o2.equals(String.valueOf(o1)))
          return false;
      }
      else if (((o1 instanceof JSONObject)) && ((o2 instanceof JSONObject))) {
        if (!o1.equals(o2))
          return false;
      }
      else if (((o1 instanceof JSONArray)) && ((o2 instanceof JSONArray))) {
        if (!o1.equals(o2))
          return false;
      }
      else if (((o1 instanceof JSONFunction)) && ((o2 instanceof JSONFunction))) {
        if (!o1.equals(o2)) {
          return false;
        }
      }
      else if ((o1 instanceof String)) {
        if (!o1.equals(String.valueOf(o2)))
          return false;
      }
      else if ((o2 instanceof String)) {
        if (!o2.equals(String.valueOf(o1)))
          return false;
      }
      else {
        Morpher m1 = JSONUtils.getMorpherRegistry().getMorpherFor(o1.getClass());

        Morpher m2 = JSONUtils.getMorpherRegistry().getMorpherFor(o2.getClass());

        if ((m1 != null) && (m1 != IdentityObjectMorpher.getInstance())) {
          if (!o1.equals(JSONUtils.getMorpherRegistry().morph(o1.getClass(),o2)))
          {
            return false;
          }
        } else if ((m2 != null) && (m2 != IdentityObjectMorpher.getInstance())) {
          if (!JSONUtils.getMorpherRegistry().morph(o1.getClass(),o1).equals(o2))
          {
            return false;
          }
        }
        else if (!o1.equals(o2)) {
          return false;
        }
      }

    }

    return true;
  }

  public Object get(Object key) {
    if ((key instanceof String)) {
      return get((String)key);
    }
    return null;
  }

  public Object get(String key)
  {
    verifyIsNull();
    return this.properties.get(key);
  }

  public boolean getBoolean(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if (o != null) {
      if ((o.equals(Boolean.FALSE)) || (((o instanceof String)) && (((String)o).equalsIgnoreCase("false"))))
      {
        return false;
      }if ((o.equals(Boolean.TRUE)) || (((o instanceof String)) && (((String)o).equalsIgnoreCase("true"))))
      {
        return true;
      }
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a Boolean.");
  }

  public double getDouble(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if (o != null) {
      try {
        return (o instanceof Number) ? ((Number)o).doubleValue() : Double.parseDouble((String)o);
      }
      catch (Exception e) {
        throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
      }
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
  }

  public int getInt(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if (o != null) {
      return (o instanceof Number) ? ((Number)o).intValue() : (int)getDouble(key);
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
  }

  public JSONArray getJSONArray(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if ((o != null) && ((o instanceof JSONArray))) {
      return (JSONArray)o;
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a JSONArray.");
  }

  public JSONObject getJSONObject(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if (JSONNull.getInstance().equals(o))
    {
      return new JSONObject(true);
    }if ((o instanceof JSONObject)) {
      return (JSONObject)o;
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a JSONObject.");
  }

  public long getLong(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if (o != null) {
      return (o instanceof Number) ? ((Number)o).longValue() : ()getDouble(key);
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] is not a number.");
  }

  public String getString(String key)
  {
    verifyIsNull();
    Object o = get(key);
    if (o != null) {
      return o.toString();
    }
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] not found.");
  }

  public boolean has(String key)
  {
    verifyIsNull();
    return this.properties.containsKey(key);
  }

  public int hashCode() {
    int hashcode = 19;
    if (isNullObject()) {
      return hashcode + JSONNull.getInstance().hashCode();
    }

    Iterator entries = this.properties.entrySet().iterator();
    while (entries.hasNext()) {
      Map.Entry entry = (Map.Entry)entries.next();
      Object key = entry.getKey();
      Object value = entry.getValue();
      hashcode += key.hashCode() + JSONUtils.hashCode(value);
    }
    return hashcode;
  }

  public boolean isArray() {
    return false;
  }

  public boolean isEmpty()
  {
    return this.properties.isEmpty();
  }

  public boolean isNullObject()
  {
    return this.nullObject;
  }

  public Iterator keys()
  {
    verifyIsNull();
    return keySet().iterator();
  }

  public Set keySet() {
    return Collections.unmodifiableSet(this.properties.keySet());
  }

  public JSONArray names()
  {
    verifyIsNull();
    JSONArray ja = new JSONArray();
    Iterator keys = keys();
    while (keys.hasNext()) {
      ja.element(keys.next());
    }
    return ja;
  }

  public JSONArray names(JsonConfig jsonConfig)
  {
    verifyIsNull();
    JSONArray ja = new JSONArray();
    Iterator keys = keys();
    while (keys.hasNext()) {
      ja.element(keys.next(),jsonConfig);
    }
    return ja;
  }

  public Object opt(String key)
  {
    verifyIsNull();
    return key == null ? null : this.properties.get(key);
  }

  public boolean optBoolean(String key)
  {
    verifyIsNull();
    return optBoolean(key,false);
  }

  public boolean optBoolean(String key,boolean defaultValue)
  {
    verifyIsNull();
    try {
      return getBoolean(key); } catch (Exception e) {
    }
    return defaultValue;
  }

  public double optDouble(String key)
  {
    verifyIsNull();
    return optDouble(key,(0.0D / 0.0D));
  }

  public double optDouble(String key,double defaultValue)
  {
    verifyIsNull();
    try {
      Object o = opt(key);
      return (o instanceof Number) ? ((Number)o).doubleValue() : new Double((String)o).doubleValue();
    } catch (Exception e) {
    }
    return defaultValue;
  }

  public int optInt(String key)
  {
    verifyIsNull();
    return optInt(key,0);
  }

  public int optInt(String key,int defaultValue)
  {
    verifyIsNull();
    try {
      return getInt(key); } catch (Exception e) {
    }
    return defaultValue;
  }

  public JSONArray optJSONArray(String key)
  {
    verifyIsNull();
    Object o = opt(key);
    return (o instanceof JSONArray) ? (JSONArray)o : null;
  }

  public JSONObject optJSONObject(String key)
  {
    verifyIsNull();
    Object o = opt(key);
    return (o instanceof JSONObject) ? (JSONObject)o : null;
  }

  public long optLong(String key)
  {
    verifyIsNull();
    return optLong(key,0L);
  }

  public long optLong(String key,long defaultValue)
  {
    verifyIsNull();
    try {
      return getLong(key); } catch (Exception e) {
    }
    return defaultValue;
  }

  public String optString(String key)
  {
    verifyIsNull();
    return optString(key,"");
  }

  public String optString(String key,String defaultValue)
  {
    verifyIsNull();
    Object o = opt(key);
    return o != null ? o.toString() : defaultValue;
  }

  public Object put(Object key,Object value) {
    if (key == null) {
      throw new IllegalArgumentException("key is null.");
    }
    Object prevIoUs = this.properties.get(key);
    element(String.valueOf(key),value);
    return prevIoUs;
  }

  public void putAll(Map map) {
    putAll(map,new JsonConfig());
  }

  public void putAll(Map map,JsonConfig jsonConfig) {
    if ((map instanceof JSONObject)) {
      Iterator entries = map.entrySet().iterator();
      while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry)entries.next();
        String key = (String)entry.getKey();
        Object value = entry.getValue();
        this.properties.put(key,value);
      }
    } else {
      Iterator entries = map.entrySet().iterator();
      while (entries.hasNext()) {
        Map.Entry entry = (Map.Entry)entries.next();
        String key = String.valueOf(entry.getKey());
        Object value = entry.getValue();
        element(key,jsonConfig);
      }
    }
  }

  public Object remove(Object key) {
    return this.properties.remove(key);
  }

  public Object remove(String key)
  {
    verifyIsNull();
    return this.properties.remove(key);
  }

  public int size()
  {
    return this.properties.size();
  }

  public JSONArray toJSONArray(JSONArray names)
  {
    verifyIsNull();
    if ((names == null) || (names.size() == 0)) {
      return null;
    }
    JSONArray ja = new JSONArray();
    for (int i = 0; i < names.size(); i++) {
      ja.element(opt(names.getString(i)));
    }
    return ja;
  }

  public String toString()
  {
    if (isNullObject()) {
      return JSONNull.getInstance().toString();
    }
    try
    {
      Iterator keys = keys();
      StringBuffer sb = new StringBuffer("{");

      while (keys.hasNext()) {
        if (sb.length() > 1) {
          sb.append(',');
        }
        Object o = keys.next();
        sb.append(JSONUtils.quote(o.toString()));
        sb.append(':');
        sb.append(JSONUtils.valueToString(this.properties.get(o)));
      }
      sb.append('}');
      return sb.toString(); } catch (Exception e) {
    }
    return null;
  }

  public String toString(int indentFactor)
  {
    if (isNullObject()) {
      return JSONNull.getInstance().toString();
    }

    if (indentFactor == 0) {
      return toString();
    }
    return toString(indentFactor,0);
  }

  public String toString(int indentFactor,int indent)
  {
    if (isNullObject()) {
      return JSONNull.getInstance().toString();
    }

    int n = size();
    if (n == 0) {
      return "{}";
    }
    if (indentFactor == 0) {
      return toString();
    }
    Iterator keys = keys();
    StringBuffer sb = new StringBuffer("{");
    int newindent = indent + indentFactor;

    if (n == 1) {
      Object o = keys.next();
      sb.append(JSONUtils.quote(o.toString()));
      sb.append(": ");
      sb.append(JSONUtils.valueToString(this.properties.get(o),indentFactor,indent));
    } else {
      while (keys.hasNext()) {
        Object o = keys.next();
        if (sb.length() > 1)
          sb.append(",\n");
        else {
          sb.append('\n');
        }
        for (int i = 0; i < newindent; i++) {
          sb.append(' ');
        }
        sb.append(JSONUtils.quote(o.toString()));
        sb.append(": ");
        sb.append(JSONUtils.valueToString(this.properties.get(o),newindent));
      }
      if (sb.length() > 1) {
        sb.append('\n');
        for (int i = 0; i < indent; i++) {
          sb.append(' ');
        }
      }
      for (int i = 0; i < indent; i++) {
        sb.insert(0,' ');
      }
    }
    sb.append('}');
    return sb.toString();
  }

  public Collection values() {
    return Collections.unmodifiableCollection(this.properties.values());
  }

  public Writer write(Writer writer)
  {
    try
    {
      if (isNullObject()) {
        writer.write(JSONNull.getInstance().toString());

        return writer;
      }

      boolean b = false;
      Iterator keys = keys();
      writer.write(123);

      while (keys.hasNext()) {
        if (b) {
          writer.write(44);
        }
        Object k = keys.next();
        writer.write(JSONUtils.quote(k.toString()));
        writer.write(58);
        Object v = this.properties.get(k);
        if ((v instanceof JSONObject))
          ((JSONObject)v).write(writer);
        else if ((v instanceof JSONArray))
          ((JSONArray)v).write(writer);
        else {
          writer.write(JSONUtils.valueToString(v));
        }
        b = true;
      }
      writer.write(125);
      return writer; } catch (IOException e) {
    }
    throw new JSONException(e);
  }

  private JSONObject _accumulate(String key,JsonConfig jsonConfig)
  {
    if (isNullObject()) {
      throw new JSONException("Can't accumulate on null object");
    }

    if (!has(key)) {
      setInternal(key,jsonConfig);
    } else {
      Object o = opt(key);
      if ((o instanceof JSONArray))
        ((JSONArray)o).element(value,jsonConfig);
      else {
        setInternal(key,new JSONArray().element(o).element(value,jsonConfig);
      }

    }

    return this;
  }

  protected Object _processValue(Object value,JsonConfig jsonConfig) {
    if ((value instanceof JSONTokener))
      return _fromJSONTokener((JSONTokener)value,jsonConfig);
    if ((value != null) && (Enum.class.isAssignableFrom(value.getClass()))) {
      return ((Enum)value).name();
    }
    return super._processValue(value,jsonConfig);
  }

  private JSONObject _setInternal(String key,JsonConfig jsonConfig)
  {
    verifyIsNull();
    if (key == null) {
      throw new JSONException("Null key.");
    }

    if ((JSONUtils.isString(value)) && (JSONUtils.mayBeJSON(String.valueOf(value)))) {
      this.properties.put(key,value);
    }
    else if ((CycleDetectionStrategy.IGNORE_PROPERTY_OBJ != value) && (CycleDetectionStrategy.IGNORE_PROPERTY_ARR != value))
    {
      this.properties.put(key,value);
    }

    return this;
  }

  private Object processValue(Object value,JsonConfig jsonConfig) {
    if (value != null) {
      JsonValueProcessor processor = jsonConfig.findJsonValueProcessor(value.getClass());
      if (processor != null) {
        value = processor.processObjectValue(null,jsonConfig);
        if (!JsonVerifier.isValidJsonValue(value)) {
          throw new JSONException("Value is not a valid JSON value. " + value);
        }
      }
    }
    return _processValue(value,jsonConfig);
  }

  private Object processValue(String key,JsonConfig jsonConfig) {
    if (value != null) {
      JsonValueProcessor processor = jsonConfig.findJsonValueProcessor(value.getClass(),key);
      if (processor != null) {
        value = processor.processObjectValue(null,jsonConfig);
  }

  private JSONObject setInternal(String key,JsonConfig jsonConfig)
  {
    return _setInternal(key,processValue(key,jsonConfig);
  }

  private void verifyIsNull()
  {
    if (isNullObject())
      throw new JSONException("null object");
  }
}
原文链接:https://www.f2er.com/json/290473.html

猜你在找的Json相关文章