Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright 2002-2007 the original author or authors.
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  package net.sf.json;
  
  /*
  Copyright (c) 2002 JSON.org
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
  
  The Software shall be used for Good, not Evil.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
  */
  
  import java.io.Writer;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  import java.util.TreeMap;
  
  
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONNull object. A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the element and toString methods. A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.

The generic get() and opt() methods return an object, which you can cast or query for type. There are also typed get and opt methods that do type checking and type coersion for you.

The put methods adds values to an object. For example,

     myString = new JSONObject().put("JSON", "Hello, World!").toString();
produces the string {"JSON": "Hello, World"}.

The texts produced by the toString methods strictly conform to the JSON sysntax rules. The constructors are more forgiving in the texts they will accept:

  • An extra , (comma) may appear just before the closing brace.
  • Strings may be quoted with ' (single quote).
  • Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.
  • Keys can be followed by = or => as well as by :.
  • Values can be followed by ; (semicolon) as well as by , (comma).
  • Numbers may have the 0- (octal) or 0x- (hex) prefix.
  • Comments written in the slashshlash, slashstar, and hash conventions will be ignored.

Author(s):
JSON.org
 
 public final class JSONObject extends AbstractJSON implements JSONMap<String,Object>, Comparable {
 
    private static final Log log = LogFactory.getLogJSONObject.class );

   
Creates a JSONObject.
Inspects the object type to call the correct JSONObject factory method.

Parameters:
object
Throws:
JSONException if the object can not be converted to a proper JSONObject.
 
 
    public static JSONObject fromObjectObject object ) {
       return fromObjectobjectnew JsonConfig() );
    }

   
Creates a JSONObject.
Inspects the object type to call the correct JSONObject factory method.

Parameters:
object
Throws:
JSONException if the object can not be converted to a proper JSONObject.
 
    public static JSONObject fromObjectObject objectJsonConfig jsonConfig ) {
       ifobject == null || JSONUtils.isNullobject ) ){
          return new JSONObjecttrue );
       }else ifobject instanceof Enum ){
          throw new JSONException"'object' is an Enum. Use JSONArray instead" );
       }else if(object instanceof Annotation || (object.getClass().isAnnotation())){
          throw new JSONException"'object' is an Annotation." );
       }else ifobject instanceof JSONObject ){
          return _fromJSONObject( (JSONObjectobjectjsonConfig );
       }else ifobject instanceof DynaBean ){
          return _fromDynaBean( (DynaBeanobjectjsonConfig );
       }else ifobject instanceof JSONTokener ){
          return _fromJSONTokener( (JSONTokenerobjectjsonConfig );
       }else ifobject instanceof JSONString ){
          return _fromJSONString( (JSONStringobjectjsonConfig );
       }else ifobject instanceof Map ){
          return _fromMap( (MapobjectjsonConfig );
       }else ifobject instanceof String ){
          return _fromString( (StringobjectjsonConfig );
       }else if( JSONUtils.isNumberobject ) || JSONUtils.isBooleanobject )
             || JSONUtils.isStringobject ) ){
          return new JSONObject();
       }else if( JSONUtils.isArrayobject ) ){
          throw new JSONException"'object' is an array. Use JSONArray instead" );
       }else{
          return _fromBeanobjectjsonConfig );
       }
    }

   
Creates a JSONDynaBean from a JSONObject.
 
    public Object toBean() {
       return toBean(this);
    }
    public static Object toBeanJSONObject jsonObject ) {
       ifjsonObject == null || jsonObject.isNullObject() ){
          return null;
       }
 
       DynaBean dynaBean;
 
       Map props = JSONUtils.getPropertiesjsonObject );
       dynaBean = JSONUtils.newDynaBeanjsonObjectnew JsonConfig() );
       forIterator entries = jsonObject.names()
             .iterator(); entries.hasNext(); ){
          String name = (Stringentries.next();
          String key = JSONUtils.convertToJavaIdentifiernamenew JsonConfig() );
          Class type = (Classprops.getname );
          Object value = jsonObject.getname );
          try{
             if( !JSONUtils.isNullvalue ) ){
                ifvalue instanceof JSONArray ){
                   dynaBean.setkey, JSONArray.toList( (JSONArrayvalue ) );
                }else ifString.class.isAssignableFromtype )
                      || Boolean.class.isAssignableFromtype ) || JSONUtils.isNumbertype )
                      || Character.class.isAssignableFromtype )
                      || JSONFunction.class.isAssignableFromtype ) ){
                   dynaBean.setkeyvalue );
                }else{
                   dynaBean.setkeytoBean( (JSONObjectvalue ) );
                }
             }else{
                iftype.isPrimitive() ){
                   // assume assigned default value
                   .warn"Tried to assign null value to " + key + ":" + type.getName() );
                   dynaBean.setkey, JSONUtils.getMorpherRegistry()
                         .morphtypenull ) );
                }else{
                   dynaBean.setkeynull );
                }
             }
          }catchJSONException jsone ){
             throw jsone;
          }catchException e ){
             throw new JSONException"Error while setting property=" + name + " type" + typee );
          }
       }
 
       return dynaBean;
    }
 
    public Object toBeanClass beanClass ) {
       return toBean(this,beanClass);
    }

   
Creates a bean from a JSONObject, with a specific target class.
 
    public static Object toBeanJSONObject jsonObjectClass beanClass ) {
       JsonConfig jsonConfig = new JsonConfig();
       jsonConfig.setRootClassbeanClass );
       return toBeanjsonObjectjsonConfig );
    }

   
Creates a bean from a JSONObject, with a specific target class.
If beanClass is null, this method will return a graph of DynaBeans. Any attribute that is a JSONObject and matches a key in the classMap will be converted to that target class.
The classMap has the following conventions:
  • Every key must be an String.
  • Every value must be a Class.
  • A key may be a regular expression.
 
    public static Object toBeanJSONObject jsonObjectClass beanClassMap classMap ) {
       JsonConfig jsonConfig = new JsonConfig();
       jsonConfig.setRootClassbeanClass );
       jsonConfig.setClassMapclassMap );
       return toBeanjsonObjectjsonConfig );
    }
 
     private interface Property {
        boolean isWritable();
        Class type();
        String name();
     }
 
    private static class PropertyOnMap implements Property {
       private final String name;
 
       private PropertyOnMap(String name) {
          this. = name;
       }
 
       public boolean isWritable() {
          return true;
       }
 
       public String name() {
          return ;
       }
 
       public Class type() {
          return Object.class;
       }
 
       public void set(Object beanObject value) {
          ((Map)bean).put(,value);
       }
    }
 
    private static class MethodProperty implements Property {
       private final PropertyDescriptor pd;
 
       private MethodProperty(PropertyDescriptor pd) {
          this. = pd;
       }
 
       public boolean isWritable() {
          return .getWriteMethod() != null;
       }
 
       public String name() {
          return .getName();
       }
 
       public Class type() {
          return .getPropertyType();
       }
 
       public void set(Object beanObject valuethrows InvocationTargetExceptionNoSuchMethodExceptionIllegalAccessException {
          PropertyUtils.setSimplePropertybean.getName(), value );
       }
    }
 
    private static class FieldProperty implements Property {
       private final Field f;
 
       private FieldProperty(Field f) {
          this. = f;
       }
 
       public boolean isWritable() {
          return true;
       }
 
       public Class type() {
          return .getType();
       }
 
       public String name() {
          return .getName();
       }
 
       public void set(Object beanObject valuethrows InvocationTargetExceptionNoSuchMethodExceptionIllegalAccessException {
          .set(bean,value);
       }
    }


   
Creates a bean from a JSONObject, with the specific configuration.
 
    public static Object toBeanJSONObject jsonObjectJsonConfig jsonConfig ) {
       ifjsonObject == null || jsonObject.isNullObject() ){
          return null;
       }
 
       Class beanClass = jsonConfig.getRootClass();
       ifbeanClass == null ){
          return toBeanjsonObject );
       }
 
       Object bean;
       try{
          ifbeanClass.isInterface() ){
             if( !Map.class.isAssignableFrombeanClass ) ){
                throw new JSONException"beanClass is an interface. " + beanClass );
             }else{
                bean = new HashMap();
             }
          }else{
             bean = jsonConfig.getNewBeanInstanceStrategy()
                   .newInstancebeanClassjsonObject );
          }
       }catchJSONException jsone ){
          throw jsone;
       }catchException e ){
          throw new JSONExceptione );
       }
 
       return toBean(jsonObject,bean,jsonConfig);
    }
 
    private static Property getProperty(Class beanClassObject beanString keyJsonConfig jsonConfigthrows IllegalAccessExceptionInvocationTargetExceptionNoSuchMethodException {
       ifMap.class.isAssignableFrombeanClass ))
          return new PropertyOnMap(key);
 
       key = jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? key
             : JSONUtils.convertToJavaIdentifierkeyjsonConfig );
 
       try {
          return new FieldProperty(bean.getClass().getField(key));
       } catch (NoSuchFieldException e) {
          return new MethodProperty(PropertyUtils.getPropertyDescriptorbeankey ));
       }
    }

   
Creates a bean from a JSONObject, with the specific configuration.
 
    public static Object toBeanJSONObject jsonObjectObject beanJsonConfig jsonConfig ) {
       ifjsonObject == null || jsonObject.isNullObject() || bean == null ){
          return bean;
       }
 
       Class rootClass = bean.getClass();
       ifrootClass.isInterface() ){
          throw new JSONException"Root bean is an interface. " + rootClass );
       }
 
       Map classMap = jsonConfig.getClassMap();
       ifclassMap == null ){
          classMap = .;
       }
 
       Map props = JSONUtils.getPropertiesjsonObject );
       PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
       forIterator entries = jsonObject.names().iterator(); entries.hasNext(); ){
          String name = (Stringentries.next();
          Class type = (Classprops.getname );
          Object value = jsonObject.getname );
          ifjavaPropertyFilter != null && javaPropertyFilter.applybeannamevalue ) ){
             continue;
          }
          try{
             Property pd = getProperty(rootClass,bean,name,jsonConfig);
             if( !pd.isWritable() ){
                .warn"Property '" + pd.name() + "' has no write method. SKIPPED." );
                continue;
             }
 
             if( !JSONUtils.isNullvalue ) ){
                ifvalue instanceof JSONArray){
                   ifList.class.isAssignableFrompd.type() ) ){
                      Class targetClass = findTargetClasspd.name(), classMap );
                      targetClass = targetClass == null ? findTargetClassnameclassMap )
                            : targetClass;
                      // if targetClass is null the outcome will be a List of
                      // DynaBeans
                      // targetClass = (targetClass != null) ? targetClass :
                      // beanClass;
                      JsonConfig jsc = jsonConfig.copy();
                      jsc.setRootClasstargetClass );
                      jsc.setClassMapclassMap );
                      List list = JSONArray.toList( (JSONArrayvaluejsc );
                      pd.set(bean,list);
                   }else{
                      Class innerType = JSONUtils.getInnerComponentType(pd.type());
                      Class targetInnerType = findTargetClasspd.name(), classMap );
                      ifinnerType==Object.class && targetInnerType != null
                            && targetInnerType!=Object.class ){
                         innerType = targetInnerType;
                      }
                      JsonConfig jsc = jsonConfig.copy();
                      jsc.setRootClassinnerType );
                      jsc.setClassMapclassMap );
                      Object array = JSONArray.toArray( (JSONArrayvaluejsc );
                      ifinnerType.isPrimitive() || JSONUtils.isNumberinnerType )
                            || Boolean.class==innerType
                            || JSONUtils.isStringinnerType ) ){
                         array = JSONUtils.getMorpherRegistry()
                               .morph( Array.newInstanceinnerType, 0 )
                                     .getClass(), array );
                      }else if( !array.getClass().equals(pd.type()) ){
                         if( !pd.type().equalsObject.class ) ){
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                  .getMorpherFor( Array.newInstanceinnerType, 0 )
                                        .getClass() );
                            if( IdentityObjectMorpher.getInstance()
                                  .equalsmorpher ) ){
                               ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                     new BeanMorpherinnerType, JSONUtils.getMorpherRegistry() ) );
                               JSONUtils.getMorpherRegistry()
                                     .registerMorpherbeanMorpher );
                            }
                            array = JSONUtils.getMorpherRegistry()
                                  .morph( Array.newInstanceinnerType, 0 )
                                        .getClass(), array );
                         }
                      }
                      pd.set(bean,array);
                   }
                }else ifString.class==type || JSONUtils.isBooleantype )
                      || JSONUtils.isNumbertype ) || JSONUtils.isStringtype )
                      || JSONFunction.class.isAssignableFromtype ) ){
                   ifpd != null ){
                      ifjsonConfig.isHandleJettisonEmptyElement() && "".equalsvalue ) ){
                         pd.set(bean,null);
                      }else if( !pd.type().isInstancevalue ) ){
                         Morpher morpher = JSONUtils.getMorpherRegistry()
                               .getMorpherForpd.type() );
                         if( IdentityObjectMorpher.getInstance()
                               .equalsmorpher ) ){
                            .warn"Can't transform property '" + pd.name() + "' from "
                                  + type.getName() + " into " + pd.type()
                                        .getName() + ". Will register a default BeanMorpher" );
                            JSONUtils.getMorpherRegistry()
                                  .registerMorpher(
                                        new BeanMorpherpd.type(),
                                              JSONUtils.getMorpherRegistry() ) );
                         }
                         pd.set(bean,JSONUtils.getMorpherRegistry()
                               .morphpd.type(), value ) );
                      }else{
                         pd.set(bean,value);
                      }
                   }else if(bean instanceof Map ){
                      pd.set(bean,value);
                   }else{
                      .warn"Tried to assign property " + pd.name() + ":" + type.getName()
                            + " to bean of class " + bean.getClass()
                                  .getName() );
                   }
                }else{
                   ifpd != null ){
                      Class targetClass = pd.type();
                      ifjsonConfig.isHandleJettisonSingleElementArray() ){
                         JSONArray array = new JSONArray().elementvaluejsonConfig );
                         Class newTargetClass = findTargetClasspd.name(), classMap );
                         newTargetClass = newTargetClass == null ? findTargetClassnameclassMap )
                               : newTargetClass;
                         JsonConfig jsc = jsonConfig.copy();
                         jsc.setRootClassnewTargetClass );
                         jsc.setClassMapclassMap );
                         iftargetClass.isArray() ){
                            pd.set(bean,JSONArray.toArrayarrayjsc ));
                         }else ifCollection.class.isAssignableFromtargetClass ) ){
                            pd.set(bean,JSONArray.toListarrayjsc ));
                         }else ifJSONArray.class.isAssignableFromtargetClass ) ){
                            pd.set(bean,array);
                         }else{
                            pd.set(bean,toBean( (JSONObjectvaluejsc ));
                         }
                      }else{
                         iftargetClass == Object.class ){
                            targetClass = findTargetClasspd.name(), classMap );
                            targetClass = targetClass == null ? findTargetClassnameclassMap )
                                  : targetClass;
                         }
                         JsonConfig jsc = jsonConfig.copy();
                         jsc.setRootClasstargetClass );
                         jsc.setClassMapclassMap );
                         pd.set(bean,toBean( (JSONObjectvaluejsc ));
                      }
                   }else ifbean instanceof Map ){
                      Class targetClass = findTargetClasspd.name(), classMap );
                      targetClass = targetClass == null ? findTargetClassnameclassMap )
                            : targetClass;
                      JsonConfig jsc = jsonConfig.copy();
                      jsc.setRootClasstargetClass );
                      jsc.setClassMapclassMap );
                      iftargetClass != null ){
                         pd.set(bean,toBean( (JSONObjectvaluejsc ));
                      }else{
                         pd.set(bean,toBean( (JSONObjectvalue ));
                      }
                   }else{
                      .warn"Tried to assign property " + pd.name() + ":" + type.getName()
                            + " to bean of class " + bean.getClass()
                                  .getName() );
                   }
                }
             }else{
                iftype.isPrimitive() ){
                   // assume assigned default value
                   .warn"Tried to assign null value to " + pd.name() + ":" + type.getName() );
                   pd.set(bean,JSONUtils.getMorpherRegistry().morphtypenull ));
                }else{
                   pd.set(bean,null);
                }
             }
          }catchJSONException jsone ){
             throw jsone;
          }catchException e ){
             throw new JSONException"Error while setting property=" + name + " type " + typee );
          }
       }
 
       return bean;
    }

   
Creates a JSONObject from a POJO.
Supports nested maps, POJOs, and arrays/collections.

Parameters:
bean An object with POJO conventions
Throws:
JSONException if the bean can not be converted to a proper JSONObject.
 
    private static JSONObject _fromBeanObject beanJsonConfig jsonConfig ) {
       fireObjectStartEventjsonConfig );
       if( !addInstancebean ) ){
          try{
             return jsonConfig.getCycleDetectionStrategy()
                   .handleRepeatedReferenceAsObjectbean );
          }catchJSONException jsone ){
             removeInstancebean );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }catchRuntimeException e ){
             removeInstancebean );
             JSONException jsone = new JSONExceptione );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }
       }
 
       JsonBeanProcessor processor = jsonConfig.findJsonBeanProcessorbean.getClass() );
       ifprocessor != null ){
          try{
             JSONObject json = processor.processBeanbeanjsonConfig );
             ifjson == null ){
                json = new JSONObjecttrue );
             }
             removeInstancebean );
             fireObjectEndEventjsonConfig );
             return json;
          }catchJSONException jsone ){
             removeInstancebean );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }catchRuntimeException e ){
             removeInstancebean );
             JSONException jsone = new JSONExceptione );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }
       }
 
       Collection exclusions = jsonConfig.getMergedExcludes();
       JSONObject jsonObject = new JSONObject();
       try{
          PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptorsbean );
          PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
          Class beanClass = bean.getClass();
          forint i = 0; i < pds.lengthi++ ){
             String key = pds[i].getName();
             ifexclusions.containskey ) ){
                continue;
             }
 
             ifjsonConfig.isIgnoreTransientFields() && isTransientFieldkeybeanClass ) ){
                continue;
             }
 
             Class type = pds[i].getPropertyType();
             ifpds[i].getReadMethod() != null ){
                Object value = PropertyUtils.getPropertybeankey );
                ifjsonPropertyFilter != null && jsonPropertyFilter.applybeankeyvalue ) ){
                   continue;
                }
                JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(
                      beanClasstypekey );
                ifjsonValueProcessor != null ){
                   value = jsonValueProcessor.processObjectValuekeyvaluejsonConfig );
                   if( !JsonVerifier.isValidJsonValuevalue ) ){
                      throw new JSONException"Value is not a valid JSON value. " + value );
                   }
                }
                setValuejsonObjectkeyvaluetypejsonConfig );
             }else{
                String warning = "Property '" + key + "' has no read method. SKIPPED";
                fireWarnEventwarningjsonConfig );
                .warnwarning );
             }
          }
 
          // public field
           for (Field f : bean.getClass().getFields()) {
               String key = f.getName();
               if (exclusions.contains(key)) continue;
               if (jsonConfig.isIgnoreTransientFields() && Modifier.isTransient(f.getModifiers()))   continue;
 
               Class type = f.getType();
               f.setAccessible(true); // while the field is public, the class might not be accessible
               Object value = f.get(bean);
               ifjsonPropertyFilter != null && jsonPropertyFilter.applybeankeyvalue ))       continue;
 
               JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(beanClasstypekey );
               ifjsonValueProcessor != null ){
                  value = jsonValueProcessor.processObjectValuekeyvaluejsonConfig );
                  if( !JsonVerifier.isValidJsonValuevalue ) ){
                     throw new JSONException"Value is not a valid JSON value. " + value );
                  }
               }
               setValuejsonObjectkeyvaluetypejsonConfig );
           }
       }catchJSONException jsone ){
          removeInstancebean );
          fireErrorEventjsonejsonConfig );
          throw jsone;
       }catchException e ){
          removeInstancebean );
          JSONException jsone = new JSONExceptione );
          fireErrorEventjsonejsonConfig );
          throw jsone;
       }
 
       removeInstancebean );
       fireObjectEndEventjsonConfig );
       return jsonObject;
    }
 
    private static JSONObject _fromDynaBeanDynaBean beanJsonConfig jsonConfig ) {
       fireObjectStartEventjsonConfig );
       ifbean == null ){
          fireObjectEndEventjsonConfig );
          return new JSONObjecttrue );
       }
 
       if( !addInstancebean ) ){
          try{
             return jsonConfig.getCycleDetectionStrategy()
                   .handleRepeatedReferenceAsObjectbean );
          }catchJSONException jsone ){
             removeInstancebean );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }catchRuntimeException e ){
             removeInstancebean );
             JSONException jsone = new JSONExceptione );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }
       }
 
       JSONObject jsonObject = new JSONObject();
       try{
          DynaProperty[] props = bean.getDynaClass()
                .getDynaProperties();
          Collection exclusions = jsonConfig.getMergedExcludes();
          PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
          forint i = 0; i < props.lengthi++ ){
             DynaProperty dynaProperty = props[i];
             String key = dynaProperty.getName();
             ifexclusions.containskey ) ){
                continue;
             }
             Class type = dynaProperty.getType();
             Object value = bean.getdynaProperty.getName() );
             ifjsonPropertyFilter != null && jsonPropertyFilter.applybeankeyvalue ) ){
                continue;
             }
             JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessortypekey );
             ifjsonValueProcessor != null ){
                value = jsonValueProcessor.processObjectValuekeyvaluejsonConfig );
                if( !JsonVerifier.isValidJsonValuevalue ) ){
                   throw new JSONException"Value is not a valid JSON value. " + value );
                }
             }
             setValuejsonObjectkeyvaluetypejsonConfig );
          }
       }catchJSONException jsone ){
          removeInstancebean );
          fireErrorEventjsonejsonConfig );
          throw jsone;
       }catchRuntimeException e ){
          removeInstancebean );
          JSONException jsone = new JSONExceptione );
          fireErrorEventjsonejsonConfig );
          throw jsone;
       }
 
       removeInstancebean );
       fireObjectEndEventjsonConfig );
       return jsonObject;
    }
 
    private static JSONObject _fromJSONObjectJSONObject objectJsonConfig jsonConfig ) {
       fireObjectStartEventjsonConfig );
       ifobject == null || object.isNullObject() ){
          fireObjectEndEventjsonConfig );
          return new JSONObjecttrue );
       }
 
       if( !addInstanceobject ) ){
          try{
             return jsonConfig.getCycleDetectionStrategy()
                   .handleRepeatedReferenceAsObjectobject );
          }catchJSONException jsone ){
             removeInstanceobject );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }catchRuntimeException e ){
             removeInstanceobject );
             JSONException jsone = new JSONExceptione );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }
       }
 
       JSONArray sa = object.names();
       Collection exclusions = jsonConfig.getMergedExcludes();
       JSONObject jsonObject = new JSONObject();
       PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
       forIterator i = sa.iterator(); i.hasNext(); ){
          String key = (Stringi.next();
          ifexclusions.containskey ) ){
             continue;
          }
          Object value = object.optkey );
          ifjsonPropertyFilter != null && jsonPropertyFilter.applyobjectkeyvalue ) ){
             continue;
          }
          ifjsonObject.properties.containsKeykey ) ){
             jsonObject.accumulatekeyvaluejsonConfig );
             firePropertySetEventkeyvaluetruejsonConfig );
          }else{
             jsonObject._setInternalkeyvaluejsonConfig );
             firePropertySetEventkeyvaluefalsejsonConfig );
          }
       }
 
       removeInstanceobject );
       fireObjectEndEventjsonConfig );
       return jsonObject;
    }
 
    private static JSONObject _fromJSONStringJSONString stringJsonConfig jsonConfig ) {
       return _fromJSONTokenernew JSONTokenerstring.toJSONString() ), jsonConfig );
    }
 
    private static JSONObject _fromJSONTokenerJSONTokener tokenerJsonConfig jsonConfig ) {
       fireObjectStartEventjsonConfig );
 
       try{
          char c;
          String key;
          Object value;
 
          iftokener.matches"null.*" ) ){
             fireObjectEndEventjsonConfig );
             return new JSONObjecttrue );
          }
 
          iftokener.nextClean() != '{' ){
             throw tokener.syntaxError"A JSONObject text must begin with '{'" );
          }
 
          Collection exclusions = jsonConfig.getMergedExcludes();
          PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
          JSONObject jsonObject = new JSONObject();
          for( ;; ){
             c = tokener.nextClean();
             switchc ){
                case 0:
                   throw tokener.syntaxError"A JSONObject text must end with '}'" );
                case '}':
                   fireObjectEndEventjsonConfig );
                   return jsonObject;
                default:
                   tokener.back();
                   key = tokener.nextValuejsonConfig )
                         .toString();
             }
 
             /*
              * The key is followed by ':'. We will also tolerate '=' or '=>'.
              */
 
             c = tokener.nextClean();
             ifc == '=' ){
                iftokener.next() != '>' ){
                   tokener.back();
                }
             }else ifc != ':' ){
                throw tokener.syntaxError"Expected a ':' after a key" );
             }
             Object v = tokener.nextValuejsonConfig );
             if( !JSONUtils.isFunctionHeaderv ) ){
                ifexclusions.containskey ) ){
                   switchtokener.nextClean() ){
                      case ';':
                      case ',':
                         iftokener.nextClean() == '}' ){
                            fireObjectEndEventjsonConfig );
                            return jsonObject;
                         }
                         tokener.back();
                         break;
                      case '}':
                         fireObjectEndEventjsonConfig );
                         return jsonObject;
                      default:
                         throw tokener.syntaxError"Expected a ',' or '}'" );
                   }
                   continue;
                }
                ifjsonPropertyFilter == null || !jsonPropertyFilter.applytokenerkeyv ) ){
                   ifv instanceof String && JSONUtils.mayBeJSON( (Stringv ) ){
                      value = . + v + .;
                      ifjsonObject.properties.containsKeykey ) ){
                         jsonObject.accumulatekeyvaluejsonConfig );
                         firePropertySetEventkeyvaluetruejsonConfig );
                      }else{
                         jsonObject.elementkeyvaluejsonConfig );
                         firePropertySetEventkeyvaluefalsejsonConfig );
                      }
                   }else{
                      ifjsonObject.properties.containsKeykey ) ){
                         jsonObject.accumulatekeyvjsonConfig );
                         firePropertySetEventkeyvtruejsonConfig );
                      }else{
                         jsonObject.elementkeyvjsonConfig );
                         firePropertySetEventkeyvfalsejsonConfig );
                      }
                   }
                }
             }else{
                // read params if any
                String params = JSONUtils.getFunctionParams( (Stringv );
                // read function text
                int i = 0;
                StringBuffer sb = new StringBuffer();
                for( ;; ){
                   char ch = tokener.next();
                   ifch == 0 ){
                      break;
                   }
                   ifch == '{' ){
                      i++;
                   }
                   ifch == '}' ){
                      i--;
                   }
                   sb.appendch );
                   ifi == 0 ){
                      break;
                   }
                }
                ifi != 0 ){
                   throw tokener.syntaxError"Unbalanced '{' or '}' on prop: " + v );
                }
                // trim '{' at start and '}' at end
                String text = sb.toString();
                text = text.substring( 1, text.length() - 1 )
                      .trim();
                value = new JSONFunction(
                      (params != null) ? StringUtils.splitparams"," ) : nulltext );
                ifjsonPropertyFilter == null || !jsonPropertyFilter.applytokenerkeyvalue ) ){
                   ifjsonObject.properties.containsKeykey ) ){
                      jsonObject.accumulatekeyvaluejsonConfig );
                      firePropertySetEventkeyvaluetruejsonConfig );
                   }else{
                      jsonObject.elementkeyvaluejsonConfig );
                      firePropertySetEventkeyvaluefalsejsonConfig );
                   }
                }
             }
 
             /*
              * Pairs are separated by ','. We will also tolerate ';'.
              */
 
             switchtokener.nextClean() ){
                case ';':
                case ',':
                   iftokener.nextClean() == '}' ){
                      fireObjectEndEventjsonConfig );
                      return jsonObject;
                   }
                   tokener.back();
                   break;
                case '}':
                   fireObjectEndEventjsonConfig );
                   return jsonObject;
                default:
                   throw tokener.syntaxError"Expected a ',' or '}'" );
             }
          }
       }catchJSONException jsone ){
          fireErrorEventjsonejsonConfig );
          throw jsone;
       }
    }
 
    private static JSONObject _fromMapMap mapJsonConfig jsonConfig ) {
       fireObjectStartEventjsonConfig );
       ifmap == null ){
          fireObjectEndEventjsonConfig );
          return new JSONObjecttrue );
       }
 
       if( !addInstancemap ) ){
          try{
             return jsonConfig.getCycleDetectionStrategy()
                   .handleRepeatedReferenceAsObjectmap );
          }catchJSONException jsone ){
             removeInstancemap );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }catchRuntimeException e ){
             removeInstancemap );
             JSONException jsone = new JSONExceptione );
             fireErrorEventjsonejsonConfig );
             throw jsone;
          }
      }
      Collection exclusions = jsonConfig.getMergedExcludes();
      JSONObject jsonObject = new JSONObject();
      PropertyFilter jsonPropertyFilter = jsonConfig.getJsonPropertyFilter();
      try{
         forIterator entries = map.entrySet()
               .iterator(); entries.hasNext(); ){
            Map.Entry entry = (Map.Entryentries.next();
            Object k = entry.getKey();
            String key = (k instanceof String) ? (Stringk : String.valueOfk );
            ifexclusions.containskey ) ){
               continue;
            }
            Object value = entry.getValue();
            ifjsonPropertyFilter != null && jsonPropertyFilter.applymapkeyvalue ) ){
               continue;
            }
            ifvalue != null ){
               JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(
                     value.getClass(), key );
               ifjsonValueProcessor != null ){
                  value = jsonValueProcessor.processObjectValuekeyvaluejsonConfig );
                  if( !JsonVerifier.isValidJsonValuevalue ) ){
                     throw new JSONException"Value is not a valid JSON value. " + value );
                  }
               }
               setValuejsonObjectkeyvaluevalue.getClass(), jsonConfig );
            }else{
               ifjsonObject.properties.containsKeykey ) ){
                  jsonObject.accumulatekey, JSONNull.getInstance() );
                  firePropertySetEventkey, JSONNull.getInstance(), truejsonConfig );
               }else{
                  jsonObject.elementkey, JSONNull.getInstance() );
                  firePropertySetEventkey, JSONNull.getInstance(), falsejsonConfig );
               }
            }
         }
      }catchJSONException jsone ){
         removeInstancemap );
         fireErrorEventjsonejsonConfig );
         throw jsone;
      }catchRuntimeException e ){
         removeInstancemap );
         JSONException jsone = new JSONExceptione );
         fireErrorEventjsonejsonConfig );
         throw jsone;
      }
      removeInstancemap );
      fireObjectEndEventjsonConfig );
      return jsonObject;
   }
   private static JSONObject _fromStringString strJsonConfig jsonConfig ) {
      ifstr == null || "null".compareToIgnoreCasestr ) == 0 ){
         fireObjectStartEventjsonConfig );
         fireObjectEndEventjsonConfig );
         return new JSONObjecttrue );
      }
      return _fromJSONTokenernew JSONTokenerstr ), jsonConfig );
   }

   
Locates a Class associated to a specifi key.
The key may be a regexp.
   private static Class findTargetClassString keyMap classMap ) {
      // try get first
      Class targetClass = (ClassclassMap.getkey );
      iftargetClass == null ){
         // try with regexp
         // this will hit performance as it must iterate over all the keys
         // and create a RegexpMatcher for each key
         forIterator i = classMap.entrySet()
               .iterator(); i.hasNext(); ){
            Map.Entry entry = (Map.Entryi.next();
            if( RegexpUtils.getMatcher( (Stringentry.getKey() )
                  .matcheskey ) ){
               targetClass = (Classentry.getValue();
               break;
            }
         }
      }
      return targetClass;
   }
   private static boolean isTransientFieldString nameClass beanClass ) {
      try{
         Field field = beanClass.getDeclaredFieldname );
         return (field.getModifiers() & .) == .;
      }catchException e ){
         // swallow exception
      }
      return false;
   }
   private static void setValueJSONObject jsonObjectString keyObject valueClass type,
         JsonConfig jsonConfig ) {
      boolean accumulated = false;
      ifvalue == null ){
         if( JSONUtils.isArraytype ) ){
            value = new JSONArray();
         }else if( JSONUtils.isNumbertype ) ){
            if( JSONUtils.isDoubletype ) ){
               value = new Double( 0 );
            }else{
               value = new Integer( 0 );
            }
         }else if( JSONUtils.isBooleantype ) ){
            value = .;
         }else if( JSONUtils.isStringtype ) ){
            value = "";
         }else{
            value = JSONNull.getInstance();
         }
      }
      ifjsonObject.properties.containsKeykey ) ){
         ifString.class.isAssignableFromtype ) ){
            Object o = jsonObject.optkey );
            ifo instanceof JSONArray ){
               ((JSONArrayo).addString( (Stringvalue );
            }else{
               jsonObject.properties.putkeynew JSONArray().elemento )
                     .addString( (Stringvalue ) );
            }
         }else{
            jsonObject.accumulatekeyvaluejsonConfig );
         }
         accumulated = true;
      }else{
         ifString.class.isAssignableFromtype ) ){
            jsonObject.properties.putkeyvalue );
         }else{
            jsonObject._setInternalkeyvaluejsonConfig );
         }
      }
      value = jsonObject.optkey );
      ifaccumulated ){
         JSONArray array = (JSONArrayvalue;
         value = array.getarray.size() - 1 );
      }
      firePropertySetEventkeyvalueaccumulatedjsonConfig );
   }
   // ------------------------------------------------------

   
identifies this object as null
   private boolean nullObject;

   
The Map where the JSONObject's properties are kept.
   private Map properties;

   
Construct an empty JSONObject.
   public JSONObject() {
      this. = new TreeMap();
   }

   
Creates a JSONObject that is null.
   public JSONObjectboolean isNull ) {
      this();
      this. = isNull;
   }

   
Accumulate values under a key. It is similar to the element method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

Parameters:
key A key string.
value An object to be accumulated under the key.
Returns:
this.
Throws:
JSONException If the value is an invalid number or if the key is null.
   public JSONObject accumulateString keyboolean value ) {
      return _accumulatekeyvalue ? . : .new JsonConfig() );
   }

   
Accumulate values under a key. It is similar to the element method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

Parameters:
key A key string.
value An object to be accumulated under the key.
Returns:
this.
Throws:
JSONException If the value is an invalid number or if the key is null.
   public JSONObject accumulateString keydouble value ) {
      return _accumulatekey, Double.valueOfvalue ), new JsonConfig() );
   }

   
Accumulate values under a key. It is similar to the element method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

Parameters:
key A key string.
value An object to be accumulated under the key.
Returns:
this.
Throws:
JSONException If the value is an invalid number or if the key is null.
   public JSONObject accumulateString keyint value ) {
      return _accumulatekey, Integer.valueOfvalue ), new JsonConfig() );
   }

   
Accumulate values under a key. It is similar to the element method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

Parameters:
key A key string.
value An object to be accumulated under the key.
Returns:
this.
Throws:
JSONException If the value is an invalid number or if the key is null.
   public JSONObject accumulateString keylong value ) {
      return _accumulatekey, Long.valueOfvalue ), new JsonConfig() );
   }

   
Accumulate values under a key. It is similar to the element method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

Parameters:
key A key string.
value An object to be accumulated under the key.
Returns:
this.
Throws:
JSONException If the value is an invalid number or if the key is null.
   public JSONObject accumulateString keyObject value ) {
      return _accumulatekeyvaluenew JsonConfig() );
   }

   
Accumulate values under a key. It is similar to the element method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the replace method replaces the previous value.

Parameters:
key A key string.
value An object to be accumulated under the key.
Returns:
this.
Throws:
JSONException If the value is an invalid number or if the key is null.
   public JSONObject accumulateString keyObject valueJsonConfig jsonConfig ) {
      return _accumulatekeyvaluejsonConfig );
   }
   public void accumulateAllMap map ) {
      accumulateAllmapnew JsonConfig() );
   }
   public void accumulateAllMap mapJsonConfig jsonConfig ) {
      ifmap instanceof JSONObject ){
         forIterator entries = map.entrySet()
               .iterator(); entries.hasNext(); ){
            Map.Entry entry = (Map.Entryentries.next();
            String key = (Stringentry.getKey();
            Object value = entry.getValue();
            accumulatekeyvaluejsonConfig );
         }
      }else{
         forIterator entries = map.entrySet()
               .iterator(); entries.hasNext(); ){
            Map.Entry entry = (Map.Entryentries.next();
            String key = String.valueOfentry.getKey() );
            Object value = entry.getValue();
            accumulatekeyvaluejsonConfig );
         }
      }
   }
   public void clear() {
      .clear();
   }
   public int compareToObject obj ) {
      ifobj != null && (obj instanceof JSONObject) ){
         JSONObject other = (JSONObjectobj;
         int size1 = size();
         int size2 = other.size();
         ifsize1 < size2 ){
            return -1;
         }else ifsize1 > size2 ){
            return 1;
         }else ifthis.equalsother ) ){
            return 0;
         }
      }
      return -1;
   }
   public boolean containsKeyObject key ) {
      return .containsKeykey );
   }
   public boolean containsValueObject value ) {
      return containsValuevaluenew JsonConfig() );
   }
   public boolean containsValueObject valueJsonConfig jsonConfig ) {
      try{
         value = processValuevaluejsonConfig );
      }catchJSONException e ){
         return false;
      }
      return .containsValuevalue );
   }

   
Put a key/boolean pair in the JSONObject.

Parameters:
key A key string.
value A boolean which is the value.
Returns:
this.
Throws:
JSONException If the key is null.
   public JSONObject elementString keyboolean value ) {
      verifyIsNull();
      return elementkeyvalue ? . : . );
   }

   
Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.

Parameters:
key A key string.
value A Collection value.
Returns:
this.
Throws:
JSONException
   public JSONObject elementString keyCollection value ) {
      return elementkeyvaluenew JsonConfig() );
   }

   
Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.

Parameters:
key A key string.
value A Collection value.
Returns:
this.
Throws:
JSONException
   public JSONObject elementString keyCollection valueJsonConfig jsonConfig ) {
      verifyIsNull();
      ifvalue instanceof JSONArray ){
         return setInternalkeyvaluejsonConfig );
      }else{
         return elementkey, JSONArray.fromObjectvaluejsonConfig ) );
      }
   }

   
Put a key/double pair in the JSONObject.

Parameters:
key A key string.
value A double which is the value.
Returns:
this.
Throws:
JSONException If the key is null or if the number is invalid.
   public JSONObject elementString keydouble value ) {
      verifyIsNull();
      Double d = new Doublevalue );
      JSONUtils.testValidityd );
      return elementkeyd );
   }

   
Put a key/int pair in the JSONObject.

Parameters:
key A key string.
value An int which is the value.
Returns:
this.
Throws:
JSONException If the key is null.
   public JSONObject elementString keyint value ) {
      verifyIsNull();
      return elementkeynew Integervalue ) );
   }

   
Put a key/long pair in the JSONObject.

Parameters:
key A key string.
value A long which is the value.
Returns:
this.
Throws:
JSONException If the key is null.
   public JSONObject elementString keylong value ) {
      verifyIsNull();
      return elementkeynew Longvalue ) );
   }

   
Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map.

Parameters:
key A key string.
value A Map value.
Returns:
this.
Throws:
JSONException
   public JSONObject elementString keyMap value ) {
      return elementkeyvaluenew JsonConfig() );
   }

   
Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map.

Parameters:
key A key string.
value A Map value.
Returns:
this.
Throws:
JSONException
   public JSONObject elementString keyMap valueJsonConfig jsonConfig ) {
      verifyIsNull();
      ifvalue instanceof JSONObject ){
         return setInternalkeyvaluejsonConfig );
      }else{
         return elementkey, JSONObject.fromObjectvaluejsonConfig ), jsonConfig );
      }
   }

   
Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if it is present.
If there is a previous value assigned to the key, it will call accumulate.

Parameters:
key A key string.
value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull object.
Returns:
this.
Throws:
JSONException If the value is non-finite number or if the key is null.
   public JSONObject elementString keyObject value ) {
      return elementkeyvaluenew JsonConfig() );
   }

   
Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if it is present.
If there is a previous value assigned to the key, it will call accumulate.

Parameters:
key A key string.
value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull object.
Returns:
this.
Throws:
JSONException If the value is non-finite number or if the key is null.
   public JSONObject elementString keyObject valueJsonConfig jsonConfig ) {
      verifyIsNull();
      ifkey == null ){
         throw new JSONException"Null key." );
      }
      ifvalue != null ){
         value = processValuekeyvaluejsonConfig );
         setInternalkeyvaluejsonConfig );
      }else{
         removekey );
      }
      return this;
   }

   
Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.

Parameters:
key A key string.
value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull object.
Returns:
this.
Throws:
JSONException If the value is a non-finite number.
   public JSONObject elementOptString keyObject value ) {
      return elementOptkeyvaluenew JsonConfig() );
   }

   
Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.

Parameters:
key A key string.
value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull object.
Returns:
this.
Throws:
JSONException If the value is a non-finite number.
   public JSONObject elementOptString keyObject valueJsonConfig jsonConfig ) {
      verifyIsNull();
      ifkey != null && value != null ){
         elementkeyvaluejsonConfig );
      }
      return this;
   }
   public Set entrySet() {
      return .entrySet();
   }
   public boolean equalsObject obj ) {
      ifobj == this ){
         return true;
      }
      ifobj == null ){
         return false;
      }
      if( !(obj instanceof JSONObject) ){
         return false;
      }
      JSONObject other = (JSONObjectobj;
      ifisNullObject() ){
         return other.isNullObject();
      }else{
         ifother.isNullObject() ){
            return false;
         }
      }
      ifother.size() != size() ){
         return false;
      }
      forIterator keys = .keySet()
            .iterator(); keys.hasNext(); ){
         String key = (Stringkeys.next();
         if( !other.properties.containsKeykey ) ){
            return false;
         }
         Object o1 = .getkey );
         Object o2 = other.properties.getkey );
         if( JSONNull.getInstance()
               .equalso1 ) ){
            if( JSONNull.getInstance()
                  .equalso2 ) ){
               continue;
            }else{
               return false;
            }
         }else{
            if( JSONNull.getInstance()
                  .equalso2 ) ){
               return false;
            }
         }
         ifo1 instanceof String && o2 instanceof JSONFunction ){
            if( !o1.equals( String.valueOfo2 ) ) ){
               return false;
            }
         }else ifo1 instanceof JSONFunction && o2 instanceof String ){
            if( !o2.equals( String.valueOfo1 ) ) ){
               return false;
            }
         }else ifo1 instanceof JSONObject && o2 instanceof JSONObject ){
            if( !o1.equalso2 ) ){
               return false;
            }
         }else ifo1 instanceof JSONArray && o2 instanceof JSONArray ){
            if( !o1.equalso2 ) ){
               return false;
            }
         }else ifo1 instanceof JSONFunction && o2 instanceof JSONFunction ){
            if( !o1.equalso2 ) ){
               return false;
            }
         }else{
            ifo1 instanceof String ){
               if( !o1.equals( String.valueOfo2 ) ) ){
                  return false;
               }
            }else ifo2 instanceof String ){
               if( !o2.equals( String.valueOfo1 ) ) ){
                  return false;
               }
            }else{
               Morpher m1 = JSONUtils.getMorpherRegistry()
                     .getMorpherForo1.getClass() );
               Morpher m2 = JSONUtils.getMorpherRegistry()
                     .getMorpherForo2.getClass() );
               ifm1 != null && m1 != IdentityObjectMorpher.getInstance() ){
                  if( !o1.equals( JSONUtils.getMorpherRegistry()
                        .morpho1.getClass(), o2 ) ) ){
                     return false;
                  }
               }else ifm2 != null && m2 != IdentityObjectMorpher.getInstance() ){
                  if( !JSONUtils.getMorpherRegistry()
                        .morpho1.getClass(), o1 )
                        .equalso2 ) ){
                     return false;
                  }
               }else{
                  if( !o1.equalso2 ) ){
                     return false;
                  }
               }
            }
         }
      }
      return true;
   }
   public Object getObject key ) {
      ifkey instanceof String ){
         return get( (Stringkey );
      }
      return null;
   }

   
Get the value object associated with a key.

Parameters:
key A key string.
Returns:
The object associated with the key.
Throws:
JSONException if this.isNull() returns true.
   public Object getString key ) {
      verifyIsNull();
      return this..getkey );
   }

   
Get the boolean value associated with a key.

Parameters:
key A key string.
Returns:
The truth.
Throws:
JSONException if the value is not a Boolean or the String "true" or "false".
   public boolean getBooleanString key ) {
      verifyIsNull();
      Object o = getkey );
      ifo != null ){
         ifo.equals. )
               || (o instanceof String && ((Stringo).equalsIgnoreCase"false" )) ){
            return false;
         }else ifo.equals. )
               || (o instanceof String && ((Stringo).equalsIgnoreCase"true" )) ){
            return true;
         }
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a Boolean." );
   }

   
Get the double value associated with a key.

Parameters:
key A key string.
Returns:
The numeric value.
Throws:
JSONException if the key is not found or if the value is not a Number object and cannot be converted to a number.
   public double getDoubleString key ) {
      verifyIsNull();
      Object o = getkey );
      ifo != null ){
         try{
            return o instanceof Number ? ((Numbero).doubleValue()
                  : Double.parseDouble( (Stringo );
         }catchException e ){
            throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a number." );
         }
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a number." );
   }

   
Get the int value associated with a key. If the number value is too large for an int, it will be clipped.

Parameters:
key A key string.
Returns:
The integer value.
Throws:
JSONException if the key is not found or if the value cannot be converted to an integer.
   public int getIntString key ) {
      verifyIsNull();
      Object o = getkey );
      ifo != null ){
         return o instanceof Number ? ((Numbero).intValue() : (intgetDoublekey );
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a number." );
   }

   
Get the JSONArray value associated with a key.

Parameters:
key A key string.
Returns:
A JSONArray which is the value.
Throws:
JSONException if the key is not found or if the value is not a JSONArray.
   public JSONArray getJSONArrayString key ) {
      verifyIsNull();
      Object o = getkey );
      ifo != null && o instanceof JSONArray ){
         return (JSONArrayo;
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a JSONArray." );
   }

   
Get the JSONObject value associated with a key.

Parameters:
key A key string.
Returns:
A JSONObject which is the value.
Throws:
JSONException if the key is not found or if the value is not a JSONObject.
   public JSONObject getJSONObjectString key ) {
      verifyIsNull();
      Object o = getkey );
      if( JSONNull.getInstance()
            .equalso ) ){
         return new JSONObjecttrue );
      }else ifo instanceof JSONObject ){
         return (JSONObjecto;
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a JSONObject." );
   }

   
Get the long value associated with a key. If the number value is too long for a long, it will be clipped.

Parameters:
key A key string.
Returns:
The long value.
Throws:
JSONException if the key is not found or if the value cannot be converted to a long.
   public long getLongString key ) {
      verifyIsNull();
      Object o = getkey );
      ifo != null ){
         return o instanceof Number ? ((Numbero).longValue() : (longgetDoublekey );
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] is not a number." );
   }

   
Get the string associated with a key.

Parameters:
key A key string.
Returns:
A string which is the value.
Throws:
JSONException if the key is not found.
   public String getStringString key ) {
      verifyIsNull();
      Object o = getkey );
      ifo != null ){
         return o.toString();
      }
      throw new JSONException"JSONObject[" + JSONUtils.quotekey ) + "] not found." );
   }

   
Determine if the JSONObject contains a specific key.

Parameters:
key A key string.
Returns:
true if the key exists in the JSONObject.
   public boolean hasString key ) {
      verifyIsNull();
      return this..containsKeykey );
   }
   public int hashCode() {
      int hashcode = 19;
      ifisNullObject() ){
         return hashcode + JSONNull.getInstance()
               .hashCode();
      }
      forIterator entries = .entrySet()
            .iterator(); entries.hasNext(); ){
         Map.Entry entry = (Map.Entryentries.next();
         Object key = entry.getKey();
         Object value = entry.getValue();
         hashcode += key.hashCode() + JSONUtils.hashCodevalue );
      }
      return hashcode;
   }
   public boolean isArray() {
      return false;
   }
   public boolean isEmpty() {
      verifyIsNull();
      return this..isEmpty();
   }

   
Returs if this object is a null JSONObject.
   public boolean isNullObject() {
      return ;
   }

   
Get an enumeration of the keys of the JSONObject.

Returns:
An iterator of the keys.
   public Iterator keys() {
      verifyIsNull();
      return this..keySet()
            .iterator();
   }
   public Set keySet() {
      return .keySet();
   }

   
Produce a JSONArray containing the names of the elements of this JSONObject.

Returns:
A JSONArray containing the key strings, or null if the JSONObject is empty.
   public JSONArray names() {
      verifyIsNull();
      JSONArray ja = new JSONArray();
      Iterator keys = keys();
      whilekeys.hasNext() ){
         ja.elementkeys.next() );
      }
      return ja;
   }

   
Get an optional value associated with a key.

Parameters:
key A key string.
Returns:
An object which is the value, or null if there is no value.
   public Object optString key ) {
      verifyIsNull();
      return key == null ? null : this..getkey );
   }

   
Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not Boolean.TRUE or the String "true".

Parameters:
key A key string.
Returns:
The truth.
   public boolean optBooleanString key ) {
      verifyIsNull();
      return optBooleankeyfalse );
   }

   
Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is not a Boolean or the String "true" or "false" (case insensitive).

Parameters:
key A key string.
defaultValue The default.
Returns:
The truth.
   public boolean optBooleanString keyboolean defaultValue ) {
      verifyIsNull();
      try{
         return getBooleankey );
      }catchException e ){
         return defaultValue;
      }
   }

   
Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

Parameters:
key A string which is the key.
Returns:
An object which is the value.
   public double optDoubleString key ) {
      verifyIsNull();
      return optDoublekey. );
   }

   
Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

Parameters:
key A key string.
defaultValue The default.
Returns:
An object which is the value.
   public double optDoubleString keydouble defaultValue ) {
      verifyIsNull();
      try{
         Object o = optkey );
         return o instanceof Number ? ((Numbero).doubleValue()
               : Double.parseDouble((Stringo);
      }catchException e ){
         return defaultValue;
      }
   }

   
Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

Parameters:
key A key string.
Returns:
An object which is the value.
   public int optIntString key ) {
      verifyIsNull();
      return optIntkey, 0 );
   }

   
Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

Parameters:
key A key string.
defaultValue The default.
Returns:
An object which is the value.
   public int optIntString keyint defaultValue ) {
      verifyIsNull();
      try{
         return getIntkey );
      }catchException e ){
         return defaultValue;
      }
   }

   
Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not a JSONArray.

Parameters:
key A key string.
Returns:
A JSONArray which is the value.
   public JSONArray optJSONArrayString key ) {
      verifyIsNull();
      Object o = optkey );
      return o instanceof JSONArray ? (JSONArrayo : null;
   }

   
Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not a JSONObject.

Parameters:
key A key string.
Returns:
A JSONObject which is the value.
   public JSONObject optJSONObjectString key ) {
      verifyIsNull();
      Object o = optkey );
      return o instanceof JSONObject ? (JSONObjecto : null;
   }

   
Get an optional long value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

Parameters:
key A key string.
Returns:
An object which is the value.
   public long optLongString key ) {
      verifyIsNull();
      return optLongkey, 0 );
   }

   
Get an optional long value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

Parameters:
key A key string.
defaultValue The default.
Returns:
An object which is the value.
   public long optLongString keylong defaultValue ) {
      verifyIsNull();
      try{
         return getLongkey );
      }catchException e ){
         return defaultValue;
      }
   }

   
Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is coverted to a string.

Parameters:
key A key string.
Returns:
A string which is the value.
   public String optStringString key ) {
      verifyIsNull();
      return optStringkey"" );
   }

   
Get an optional string associated with a key. It returns the defaultValue if there is no such key.

Parameters:
key A key string.
defaultValue The default.
Returns:
A string which is the value.
   public String optStringString keyString defaultValue ) {
      verifyIsNull();
      Object o = optkey );
      return o != null ? o.toString() : defaultValue;
   }
   public Object putString keyObject value ) {
      ifkey == null ){
         throw new IllegalArgumentException"key is null." );
      }
      Object previous = .getkey );
      element( String.valueOfkey ), value );
      return previous;
   }
   public void putAllMap map ) {
      putAllmapnew JsonConfig() );
   }
   public void putAllMap mapJsonConfig jsonConfig ) {
      ifmap instanceof JSONObject ){
         forIterator entries = map.entrySet()
               .iterator(); entries.hasNext(); ){
            Map.Entry entry = (Map.Entryentries.next();
            String key = (Stringentry.getKey();
            Object value = entry.getValue();
            this..putkeyvalue );
         }
      }else{
         forIterator entries = map.entrySet()
               .iterator(); entries.hasNext(); ){
            Map.Entry entry = (Map.Entryentries.next();
            String key = String.valueOfentry.getKey() );
            Object value = entry.getValue();
            elementkeyvaluejsonConfig );
         }
      }
   }
   public Object removeObject key ) {
      return .removekey );
   }

   
Remove a name and its value, if present.

Parameters:
key The name to be removed.
Returns:
The value that was associated with the name, or null if there was no value.
   public Object removeString key ) {
      verifyIsNull();
      return this..removekey );
   }

   
Get the number of keys stored in the JSONObject.

Returns:
The number of keys in the JSONObject.
   public int size() {
      verifyIsNull();
      return this..size();
   }

   
Produce a JSONArray containing the values of the members of this JSONObject.

Parameters:
names A JSONArray containing a list of key strings. This determines the sequence of the values in the result.
Returns:
A JSONArray of values.
Throws:
JSONException If any of the values are non-finite numbers.
   public JSONArray toJSONArrayJSONArray names ) {
      verifyIsNull();
      ifnames == null || names.size() == 0 ){
         return null;
      }
      JSONArray ja = new JSONArray();
      forint i = 0; i < names.size(); i += 1 ){
         ja.elementthis.optnames.getStringi ) ) );
      }
      return ja;
   }

   
Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a syntactically correct JSON text, then null will be returned instead.

Warning: This method assumes that the data structure is acyclical.

Returns:
a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
   public String toString() {
      ifisNullObject() ){
         return JSONNull.getInstance()
               .toString();
      }
      try{
         Iterator keys = keys();
         StringBuffer sb = new StringBuffer"{" );
         whilekeys.hasNext() ){
            ifsb.length() > 1 ){
               sb.append',' );
            }
            Object o = keys.next();
            sb.append( JSONUtils.quoteo.toString() ) );
            sb.append':' );
            sb.append( JSONUtils.valueToStringthis..geto ) ) );
         }
         sb.append'}' );
         return sb.toString();
      }catchException e ){
         return null;
      }
   }

   
Make a prettyprinted JSON text of this JSONObject.

Warning: This method assumes that the data structure is acyclical.

Parameters:
indentFactor The number of spaces to add to each level of indentation.
Returns:
a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
Throws:
JSONException If the object contains an invalid number.
   public String toStringint indentFactor ) {
      ifisNullObject() ){
         return JSONNull.getInstance()
               .toString();
      }
      ifindentFactor == 0 ){
         return this.toString();
      }
      return toStringindentFactor, 0 );
   }

   
Make a prettyprinted JSON text of this JSONObject.

Warning: This method assumes that the data structure is acyclical.

Parameters:
indentFactor The number of spaces to add to each level of indentation.
indent The indentation of the top level.
Returns:
a printable, displayable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
Throws:
JSONException If the object contains an invalid number.
   public String toStringint indentFactorint indent ) {
      ifisNullObject() ){
         return JSONNull.getInstance()
               .toString();
      }
      int i;
      int n = size();
      ifn == 0 ){
         return "{}";
      }
      ifindentFactor == 0 ){
         return this.toString();
      }
      Iterator keys = keys();
      StringBuffer sb = new StringBuffer"{" );
      int newindent = indent + indentFactor;
      Object o;
      ifn == 1 ){
         o = keys.next();
         sb.append( JSONUtils.quoteo.toString() ) );
         sb.append": " );
         sb.append( JSONUtils.valueToStringthis..geto ), indentFactorindent ) );
      }else{
         whilekeys.hasNext() ){
            o = keys.next();
            ifsb.length() > 1 ){
               sb.append",\n" );
            }else{
               sb.append'\n' );
            }
            fori = 0; i < newindenti += 1 ){
               sb.append' ' );
            }
            sb.append( JSONUtils.quoteo.toString() ) );
            sb.append": " );
            sb.append( JSONUtils.valueToStringthis..geto ), indentFactornewindent ) );
         }
         ifsb.length() > 1 ){
            sb.append'\n' );
            fori = 0; i < indenti += 1 ){
               sb.append' ' );
            }
         }
         fori = 0; i < indenti += 1 ){
            sb.insert( 0, ' ' );
         }
      }
      sb.append'}' );
      return sb.toString();
   }
   public Collection values() {
      return Collections.unmodifiableCollection.values() );
   }

   
Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added.

Warning: This method assumes that the data structure is acyclical.

Returns:
The writer.
Throws:
JSONException
   protected void writeWriter writerWritingVisitor visitor ) throws IOException {
       ifisNullObject() ){
          writer.write( JSONNull.getInstance().toString() );
           return;
       }
       boolean b = false;
       Iterator keys = keys();
       writer.write'{' );
       whilekeys.hasNext() ){
          ifb ){
             writer.write',' );
          }
          Object k = keys.next();
          writer.write( JSONUtils.quotek.toString() ) );
          writer.write':' );
          Object v = this..getk );
          ifv instanceof JSON ){
              visitor.on((JSON)v,writer);
          }else{
              visitor.on(v,writer);
          }
          b = true;
       }
       writer.write'}' );
   }
   private JSONObject _accumulateString keyObject valueJsonConfig jsonConfig ) {
      ifisNullObject() ){
         throw new JSONException"Can't accumulate on null object" );
      }
      if( !haskey ) ){
         setInternalkeyvaluejsonConfig );
      }else{
         Object o = optkey );
         ifo instanceof JSONArray ){
            ((JSONArrayo).elementvaluejsonConfig );
         }else{
            setInternalkeynew JSONArray().elemento )
                  .elementvaluejsonConfig ), jsonConfig );
         }
      }
      return this;
   }
   private Object _processValueObject valueJsonConfig jsonConfig ) {
      if( (value != null && Class.class.isAssignableFromvalue.getClass() ))
            || value instanceof Class ){
         return ((Classvalue).getName();
      }else ifvalue instanceof JSON ){
         return JSONSerializer.toJSONvaluejsonConfig );
      }else if( JSONUtils.isFunctionvalue ) ){
         ifvalue instanceof String ){
            value = JSONFunction.parse( (Stringvalue );
         }
         return value;
      }else ifvalue instanceof JSONString ){
         return JSONSerializer.toJSON(valuejsonConfig );
      }else if( JSONUtils.isArrayvalue ) ){
         return JSONArray.fromObjectvaluejsonConfig );
      }else if( JSONUtils.isStringvalue ) ){
         String str = String.valueOfvalue );
         ifvalue == null ){
            return "";
         }else{
            return str;
         }
      }else if( JSONUtils.isNumbervalue ) ){
         JSONUtils.testValidityvalue );
         return JSONUtils.transformNumber( (Numbervalue );
      }else if( JSONUtils.isBooleanvalue ) ){
         return value;
      }else ifvalue != null && Enum.class.isAssignableFromvalue.getClass() ) ){
         return String.valueOf(value);
      }else{
         return fromObjectvaluejsonConfig );
      }
   }

   
Put a key/value pair in the JSONObject.

Parameters:
key A key string.
value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull object.
Returns:
this.
Throws:
JSONException If the value is non-finite number or if the key is null.
   private JSONObject _setInternalString keyObject valueJsonConfig jsonConfig ) {
      verifyIsNull();
      ifkey == null ){
         throw new JSONException"Null key." );
      }
      this..putkey_processValuevaluejsonConfig ) );
      return this;
   }
   private Object processValueObject valueJsonConfig jsonConfig ) {
      ifvalue != null ){
         JsonValueProcessor processor = jsonConfig.findJsonValueProcessorvalue.getClass() );
         ifprocessor != null ){
            value = processor.processObjectValuenullvaluejsonConfig );
            if( !JsonVerifier.isValidJsonValuevalue ) ){
               throw new JSONException"Value is not a valid JSON value. " + value );
            }
         }
      }
      return _processValuevaluejsonConfig );
   }
   private Object processValueString keyObject valueJsonConfig jsonConfig ) {
      ifvalue != null ){
         JsonValueProcessor processor = jsonConfig.findJsonValueProcessorvalue.getClass(), key );
         ifprocessor != null ){
            value = processor.processObjectValuenullvaluejsonConfig );
            if( !JsonVerifier.isValidJsonValuevalue ) ){
               throw new JSONException"Value is not a valid JSON value. " + value );
            }
         }
      }
      return _processValuevaluejsonConfig );
   }

   
Put a key/value pair in the JSONObject.

Parameters:
key A key string.
value An object which is the value. It should be of one of these types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull object.
Returns:
this.
Throws:
JSONException If the value is non-finite number or if the key is null.
   private JSONObject setInternalString keyObject valueJsonConfig jsonConfig ) {
      return _setInternalkeyprocessValuekeyvaluejsonConfig ), jsonConfig );
   }

   
Checks if this object is a "null" object.
   private void verifyIsNull() {
      ifisNullObject() ){
         throw new JSONException"null object" );
      }
   }
New to GrepCode? Check out our FAQ X