Creates a new MorphDynaBean from a JSONObject. The MorphDynaBean will have
all the properties of the original JSONObject with the most accurate type.
Values of properties are not copied.
343041
public static DynaBean newDynaBean( JSONObject jsonObject, JsonConfig jsonConfig ) {
      Map props = getProperties( jsonObject );
      for( Iterator entries = props.entrySet()
            .iterator(); entries.hasNext(); ){
         Map.Entry entry = (Map.Entry) entries.next();
         String key = (String) entry.getKey();
         if( !JSONUtils.isJavaIdentifier( key ) ){
            String parsedKey = JSONUtils.convertToJavaIdentifier( key, jsonConfig );
            if( parsedKey.compareTo( key ) != 0 ){
               props.put( parsedKey, props.remove( key ) );
            }
         }
      }
      MorphDynaClass dynaClass = new MorphDynaClass( props );
      MorphDynaBean dynaBean = null;
      try{
         dynaBean = (MorphDynaBean) dynaClass.newInstance();
         dynaBean.setDynaBeanClass( dynaClass );
      }catch( Exception e ){
         throw new JSONException( e );
      }
      return dynaBean;
   }
842108
public JSONObject construct(){
        JSONObject payload = new JSONObject();
        payload.put("dnd_enabled", dndEnabled ? 1 : 0);
        payload.put("map_present", mapPresent ? 1 : 0);
        payload.put("clean_area", cleanArea);
        payload.put("fan_power", fanPower);
        payload.put("msg_ver", msgVersion);
        payload.put("in_cleaning", inCleaning ? 1 : 0);
        payload.put("error_code", errorCode.getCode());
        payload.put("state", state.getState());
        payload.put("battery", battery);
        payload.put("msg_seq", msgSeq);
        payload.put("clean_time", cleanTime);
        return payload;
    }
1114302
public static Object toBean( JSONObject 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 );
            }else{
               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();
      for( Iterator entries = jsonObject.names( jsonConfig )
            .iterator(); 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 ) ){
               // no type info available for conversion
               if( JSONUtils.isNull( value ) ){
                  setProperty( bean, key, value, jsonConfig );
               }else if( value instanceof JSONArray ){
                  setProperty( bean, key, convertPropertyValueToCollection( key, value, jsonConfig, name,
                        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, key, null, jsonConfig );
                  }else{
                     setProperty( bean, key, value, jsonConfig );
                  }
               }else{
                  Class targetClass = resolveClass(classMap, key, name, type);
                  JsonConfig jsc = jsonConfig.copy();
                  jsc.setRootClass( targetClass );
                  jsc.setClassMap( classMap );
                  if( targetClass != null ){
                     setProperty( bean, key, toBean( (JSONObject) value, jsc ), jsonConfig );
                  }else{
                     setProperty( bean, key, 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, key, convertPropertyValueToCollection( key, value,
                                 jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig );
                        }else if( Set.class.isAssignableFrom( pd.getPropertyType() ) ){
                           setProperty( bean, key, convertPropertyValueToCollection( key, value,
                                 jsonConfig, name, classMap, pd.getPropertyType() ), jsonConfig );
                        }else{
                           setProperty( bean, key, convertPropertyValueToArray( key, value,
                                 targetType, jsonConfig, 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, key, null, jsonConfig );
                           }else if( !targetType.isInstance( value ) ){
                              setProperty( bean, key, morphPropertyValue( key, value, type,
                                    targetType ), jsonConfig );
                           }else{
                              setProperty( bean, key, value, jsonConfig );
                           }
                        }else if( beanClass == null || bean instanceof Map ){
                           setProperty( bean, key, value, 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 = resolveClass(classMap, key, name, type);
                           JsonConfig jsc = jsonConfig.copy();
                           jsc.setRootClass( newTargetClass );
                           jsc.setClassMap( classMap );
                           if( targetType.isArray() ){
                              setProperty( bean, key, JSONArray.toArray( array, jsc ), jsonConfig );
                           }else if( JSONArray.class.isAssignableFrom( targetType ) ){
                              setProperty( bean, key, array, jsonConfig );
                           }else if( List.class.isAssignableFrom( targetType )
                                 || Set.class.isAssignableFrom( targetType ) ){
                              jsc.setCollectionType( targetType );
                              setProperty( bean, key, JSONArray.toCollection( array, jsc ),
                                    jsonConfig );
                           }else{
                              setProperty( bean, key, toBean( (JSONObject) value, jsc ), 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, key, toBean( (JSONObject) value, jsc ), jsonConfig );
                        }
                     }
                  }else{
                     if( type.isPrimitive() ){
                        // assume assigned default value
                        log.warn( "Tried to assign null value to " + key + ":" + type.getName() );
                        setProperty( bean, key, JSONUtils.getMorpherRegistry()
                              .morph( type, null ), jsonConfig );
                     }else{
                        setProperty( bean, key, null, jsonConfig );
                     }
                  }
               }else{
                  // pd is null
                  if( !JSONUtils.isNull( value ) ){
                     if( value instanceof JSONArray ){
                        setProperty( bean, key, convertPropertyValueToCollection( key, value,
                              jsonConfig, name, classMap, List.class ), 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, key, value, jsonConfig );
                        }else{
                           log.warn( "Tried to assign property " + key + ":" + type.getName()
                                 + " to bean of class " + bean.getClass()
                                       .getName() );
                        }
                     }else{
                        if( jsonConfig.isHandleJettisonSingleElementArray() ){
                           Class newTargetClass = resolveClass(classMap, key, name, type);
                           JsonConfig jsc = jsonConfig.copy();
                           jsc.setRootClass( newTargetClass );
                           jsc.setClassMap( classMap );
                           setProperty( bean, key, toBean( (JSONObject) value, jsc ), jsonConfig );
                        }else{
                           setProperty( bean, key, value, jsonConfig );
                        }
                     }
                  }else{
                     if( type.isPrimitive() ){
                        // assume assigned default value
                        log.warn( "Tried to assign null value to " + key + ":" + type.getName() );
                        setProperty( bean, key, JSONUtils.getMorpherRegistry()
                              .morph( type, null ), jsonConfig );
                     }else{
                        setProperty( bean, key, null, jsonConfig );
                     }
                  }
               }
            }
         }catch( JSONException jsone ){
            throw jsone;
         }catch( Exception e ){
            throw new JSONException( "Error while setting property=" + name + " type " + type, e );
         }
      }

      return bean;
   }
1010580
private Object exctractJsonifiedValue(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts)
            throws AttributeNotFoundException {
        if (pValue.getClass().isPrimitive() || FINAL_CLASSES.contains(pValue.getClass()) || pValue instanceof JSONAware) {
            // No further diving, use these directly
            return pValue;
        } else {
            // For the rest we build up a JSON map with the attributes as keys and the value are
            List<String> attributes = extractBeanAttributes(pValue);
            if (attributes.size() > 0) {
                return extractBeanValues(pConverter, pValue, pPathParts, attributes);
            } else {
                // No further attributes, return string representation
                return pValue.toString();
            }
        }
    }
30503
def instantiate(data, blueprint):
    

    Validator = jsonschema.validators.validator_for(blueprint)
    blueprinter = extend(Validator)(blueprint)
    return blueprinter.instantiate(data)
948882
@SuppressWarnings("unchecked")
    public static <T> T[] jsonArrayToArray(final JSONArray jsonArray, final Class<? extends T[]> newType) {
        if (null == jsonArray) {
            return (T[]) new Object[]{};
        }

        final int newLength = jsonArray.length();
        final Object[] original = new Object[newLength];

        for (int i = 0; i < newLength; i++) {
            original[i] = jsonArray.opt(i);
        }

        return Arrays.copyOf(original, newLength, newType);
    }
191054
public final DataModel fromJson(final InputStream resource) {
		ObjectMapper mapper = new ObjectMapper();
		mapper
			.addMixInAnnotations(DataType.class, DataTypeConfigMixin.class);
		mapper
			.addMixInAnnotations(ObjectDataType.class, ObjectDataTypeConfigMixin.class);
		try {
			return mapper.readValue(resource, DataModel.class);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
1306560
private JSONObject jsonFromElement(final AtlasElement element) throws JSONException {
        final ObjectNode objectNode = this.objectNodeFromElement(element);

        try {
            return new JSONObject(new JSONTokener(MAPPER.writeValueAsString(objectNode)));
        } catch (IOException ioe) {
            // repackage this as a JSONException...seems sensible as the caller will only know about
            // the jettison object not being created
            throw new JSONException(ioe);
        }
    }
1355792
public static <T> T cloneBean(T from, Class<T> beanClass) {
        if (from == null || from instanceof Collection || from.getClass().isArray()) {
            throw new IllegalArgumentException("Only java bean class is allowed here.");
        }
        JSONObject jsonObject = (JSONObject) JSON.toJSON(from);
        return jsonObject.toJavaObject(beanClass);
    }
680590
@JsonCreator
  public static JsonOne create(
      @JsonProperty("one") String one,
      @JsonProperty("hello") String hello) {
    return builder()
        .setOne(one)
        .setHello(hello)
        .build();
  }
963590
public static function createFromJSON($json_data, $type = null)
    {
        $className = explode('\\', $type);
        $className = lcfirst(end($className));

        $allFields = parent::createFromJSON($json_data, $type);
        $compositeFields = CompositeDTOMapper::compositeFields(get_class($allFields));
        foreach ($compositeFields as $key) {
            if (isset($allFields->$key)) {
                $allFields->$key = self::synthesizeSubresource($key, $json_data[$key], $className);
            }
        }
        return $allFields;

    }
523256
public static Object toBean( JSONObject jsonObject, Class beanClass ) {
      JsonConfig jsonConfig = new JsonConfig();
      jsonConfig.setRootClass( beanClass );
      return toBean( jsonObject, jsonConfig );
   }
63022
function createObject (type, options) {
    // retrieve the test functions for each of the objects properties
    var tests = {},
        prop;
    for (prop in type) {
      if (type.hasOwnProperty(prop)) {
        tests[prop] = ducktype(type[prop]).test;
      }
    }

    // non-empty object
    var isObject = basic.object.test;
    return new DuckType({
      name: options && options.name || null,
      test: function test (object) {
        var prop;
        
        // test whether we have an object
        if (!isObject(object)) {
          return false;
        }

        // test each of the defined properties
        for (prop in tests) {
          if (tests.hasOwnProperty(prop)) {
            if (!tests[prop](object[prop])) {
              return false;
            }
          }
        }
        return true;
      }
    });
  }
654249
@Override
    public JSONObject toJSONObject()
    {
        final JSONObject object = new JSONObject();

        object.put("type", new JSONString(getNodeType().getValue()));

        if (hasMetaData())
        {
            final MetaData meta = getMetaData();

            if (false == meta.isEmpty())
            {
                object.put("meta", new JSONObject(meta.getJSO()));
            }
        }
        object.put("attributes", new JSONObject(getAttributes().getJSO()));

        final NFastArrayList<IPrimitive<?>> list = getChildNodes();

        final JSONArray children = new JSONArray();

        if (null != list)
        {
            final int size = list.size();

            for (int i = 0; i < size; i++)
            {
                final IPrimitive<?> prim = list.get(i);

                if (null != prim)
                {
                    final JSONObject make = prim.toJSONObject();

                    if (null != make)
                    {
                        children.set(children.size(), make);
                    }
                }
            }
        }
        object.put("children", children);

        object.put("storage", getStorageEngine().toJSONObject());

        return object;
    }
596939
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();
      for( Iterator entries = jsonObject.names( jsonConfig )
            .iterator(); entries.hasNext(); ){
         String name = (String) entries.next();
         Class type = (Class) props.get( name );
         Object value = jsonObject.get( name );
         if( javaPropertyFilter != null && javaPropertyFilter.apply( root, name, 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 = resolveClass(classMap, key, name, type);
                     Object newRoot = jsonConfig.getNewBeanInstanceStrategy()
                           .newInstance( targetClass, null );
                     List list = JSONArray.toList( (JSONArray) value, newRoot, jsonConfig );
                     setProperty( root, key, 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, newRoot, 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, 0 )
                                       .getClass(), array );
                        }
                     }
                     setProperty( root, key, array, 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, key, null, 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, key, JSONUtils.getMorpherRegistry()
                              .morph( pd.getPropertyType(), value ), jsonConfig );
                     }else{
                        setProperty( root, key, value, jsonConfig );
                     }
                  }else if( root instanceof Map ){
                     setProperty( root, key, value, 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 = resolveClass(classMap, key, name, type);
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy()
                              .newInstance( newTargetClass, (JSONObject) value );
                        if( targetClass.isArray() ){
                           setProperty( root, key, JSONArray.toArray( array, newRoot, jsonConfig ),
                                 jsonConfig );
                        }else if( Collection.class.isAssignableFrom( targetClass ) ){
                           setProperty( root, key, JSONArray.toList( array, newRoot, jsonConfig ),
                                 jsonConfig );
                        }else if( JSONArray.class.isAssignableFrom( targetClass ) ){
                           setProperty( root, key, array, jsonConfig );
                        }else{
                           setProperty( root, key,
                                 toBean( (JSONObject) value, newRoot, jsonConfig ), jsonConfig );
                        }
                     }else{
                        if( targetClass == Object.class ){
                           targetClass = resolveClass(classMap, key, name, type);
                           if(targetClass == null) {
                               targetClass = Object.class;
                           }
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy()
                              .newInstance( targetClass, (JSONObject) value );
                        setProperty( root, key, toBean( (JSONObject) value, newRoot, jsonConfig ),
                              jsonConfig );
                     }
                  }else if( root instanceof Map ){
                     Class targetClass = findTargetClass( key, classMap );
                     targetClass = targetClass == null ? findTargetClass( name, classMap )
                           : targetClass;
                     Object newRoot = jsonConfig.getNewBeanInstanceStrategy()
                           .newInstance( targetClass, (JSONObject) value );
                     setProperty( root, key, toBean( (JSONObject) value, newRoot, jsonConfig ),
                           jsonConfig );
                  }else{
                     log.warn( "Tried to assign property " + key + ":" + type.getName()
                           + " to bean of class " + rootClass.getName() );
                  }
               }
            }else{
               if( type.isPrimitive() ){
                  // assume assigned default value
                  log.warn( "Tried to assign null value to " + key + ":" + type.getName() );
                  setProperty( root, key, JSONUtils.getMorpherRegistry()
                        .morph( type, null ), jsonConfig );
               }else{
                  setProperty( root, key, null, jsonConfig );
               }
            }
         }catch( JSONException jsone ){
            throw jsone;
         }catch( Exception e ){
            throw new JSONException( "Error while setting property=" + name + " type " + type, e );
         }
      }

      return root;
   }
339318
def _create(self):
        

        if 'name' in self._data:
            obj_ref = self.api.add(self.obj_parent(), self.obj_type(), name=self.obj_name())
        else:
            obj_ref = self.api.add(self.obj_parent(), self.obj_type())
        self.api.commit()
        return self.api.remapIds(obj_ref)
1267415
def to_instance(self, response):
        
        klass = self.schema['title']
        cls = get_model_class(klass, api=self.__api__)
        jdict = json.loads(response.content, encoding="utf-8")
        ### check if we have a response
        properties_dict = jdict[self.schema['title']]
        # @todo: find a way to handle the data
        # validation fails if the none values are not removed
        new_dict = helpers.remove_properties_containing_None(properties_dict)
        #jdict[self.schema['title']] = new_dict
        obj = cls(new_dict)
        #obj.links = jdict[self.schema['title']]['links']
        return obj