转为实体类对象

@param <T> Bean类型
@param json JSONObject
@param beanType 实体类对象类型
@param ignoreError 是否忽略转换错误
@return 实体类对象
@since 4.3.2
517335
public static <T> T toBean(JSONObject json, Type beanType, boolean ignoreError) {
		if (null == json) {
			return null;
		}
		return json.toBean(beanType, ignoreError);
	}
786540
@Nonnull
    public static ApiError parseError(@Nullable String errorBody, int statusCode, @Nullable String message) {
        if (errorBody == null) {
            return new ApiError(null, statusCode, message);
        }

        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<CompatibilityApiError> oldApiErrorJsonAdapter = moshi.adapter(CompatibilityApiError.class).failOnUnknown();
        try {
             return new ApiError(oldApiErrorJsonAdapter.fromJson(errorBody), statusCode);
        } catch (IOException | JsonDataException exception) {
            // Not old type of error, move on
        }

        JsonAdapter<ApiError> apiErrorJsonAdapter = moshi.adapter(ApiError.class).failOnUnknown();
        try {
            return apiErrorJsonAdapter.fromJson(errorBody);
        } catch (IOException | JsonDataException exception) {
            return new ApiError(null, statusCode, "Unknown Error");
        }
    }
1042146
private JSONObject errorForUnwrappedException(Exception e, JmxRequest pJmxReq) {
        Throwable cause = e.getCause();
        int code = cause instanceof IllegalArgumentException ? 400 : cause instanceof SecurityException ? 403 : 500;
        return getErrorJSON(code,cause, pJmxReq);
    }
757359
@SuppressWarnings("unchecked")
    protected JsonObject paramError(Map<String, Object> errors) {
        JsonObject json = JsonObject.create();
        json.setStatus(GlobalResponseStatusMsg.SYSTEM_ERROR.getMessage().getCode());
        Map<String, Object> error = new HashMap<String, Object>();
        error.put(WebResponseConstant.MESSAGE_FIELD, errors);
        json.setStatusInfo(error);
        return json;
    }
276980
@SuppressWarnings("unchecked")
    public <T> T readAsObject(byte[] content, Class<T> type) {
        try {
            if (content == null || content.length == 0 || type == null) {
                log.debug("content为{}，type为：{}", content, type);
                return null;
            } else if (type.equals(String.class)) {
                return (T) new String(content);
            }
            return MAPPER.readValue(content, type);
        } catch (Exception e) {
            log.error("json解析失败，失败原因：", e);
            return null;
        }
    }
898262
private static JSONObject genError(Integer code, String message) throws JSONException {
        // TODO: HTTP-Status (404, etc), for now return status line
        return new JSONObject("{error: {code: \"" + code.toString() + "\", message: \"" + message + "\"}}");
    }
920738
private Object parseBean(Map<String, Object> input, Class<?> beanType) throws Exception {
        String propName = "";
        try {
            SerDeserializer deser = settings.getDeserializers().findDeserializer(beanType);
            MetaBean metaBean = deser.findMetaBean(beanType);
            BeanBuilder<?> builder = deser.createBuilder(beanType, metaBean);
            for (Entry<String, Object> entry : input.entrySet()) {
                // property name
                propName = entry.getKey();
                MetaProperty<?> metaProp = deser.findMetaProperty(beanType, metaBean, propName);
                // ignore unknown properties
                if (metaProp != null && !metaProp.style().isDerived()) {
                    Object value = parseObject(
                            entry.getValue(), SerOptional.extractType(metaProp, beanType), metaProp, beanType, null);
                    deser.setValue(builder, metaProp, SerOptional.wrapValue(metaProp, beanType, value));
                }
                propName = "";
            }
            return deser.build(beanType, builder);
        } catch (Exception ex) {
            throw new IllegalArgumentException(
                    "Error parsing bean: " + beanType.getName() + "::" + propName + ", " + ex.getMessage(), ex);
        }
    }
1033948
public static <T> T toBean(String jsonStr, Class<T> beanClass) {
        requireNonNull(jsonStr, "jsonStr is null");
        JSONObject jo = JSON.parseObject(jsonStr);
        jo.put(JSON.DEFAULT_TYPE_KEY, beanClass.getName());
        return JSON.parseObject(jo.toJSONString(), beanClass);
    }
893394
@Description("Decodes json to an exception and throws it")
    @ScalarFunction(value = "fail", hidden = true)
    @SqlType("unknown")
    public static boolean failWithException(@SqlType(StandardTypes.JSON) Slice failureInfoSlice)
    {
        FailureInfo failureInfo = JSON_CODEC.fromJson(failureInfoSlice.getBytes());
        // wrap the failure in a new exception to append the current stack trace
        throw new PrestoException(StandardErrorCode.GENERIC_USER_ERROR, failureInfo.toException());
    }
205886
public static <T> T fillBeanWithMapIgnoreCase(Map<?, ?> map, T bean, boolean isIgnoreError) {
		return fillBeanWithMap(map, bean, CopyOptions.create().setIgnoreCase(true).setIgnoreError(isIgnoreError));
	}
782310
public <T> T getBean(K key, Class<T> beanType) {
		final JSONObject obj = getJSONObject(key);
		return (null == obj) ? null : obj.toBean(beanType);
	}
908024
public static Map<String, Object> beanToMap(Object bean, boolean isToUnderlineCase, boolean ignoreNullValue) {
		return beanToMap(bean, new LinkedHashMap<String, Object>(), isToUnderlineCase, ignoreNullValue);
	}
1228995
public <T> T getBean(Class<T> beanType) throws BeansException {
        return beanType.cast(BeanFactoryUtils.beanOfTypeIncludingAncestors(this, beanType));
    }
161592
public <T> T fromJson(@Nullable String jsonString, JavaType javaType) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}

		try {
			return (T) mapper.readValue(jsonString, javaType);
		} catch (IOException e) {
			logger.warn("parse json string error:" + jsonString, e);
			return null;
		}
	}
869308
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @NonNull
    private JSONObject collectMediaCodecList() throws JSONException {
        prepare();
        final MediaCodecInfo[] infos;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //noinspection deprecation
            final int codecCount = MediaCodecList.getCodecCount();
            infos = new MediaCodecInfo[codecCount];
            for (int codecIdx = 0; codecIdx < codecCount; codecIdx++) {
                //noinspection deprecation
                infos[codecIdx] = MediaCodecList.getCodecInfoAt(codecIdx);
            }
        } else {
            infos = new MediaCodecList(MediaCodecList.ALL_CODECS).getCodecInfos();
        }

        final JSONObject result = new JSONObject();
        for (int i = 0; i < infos.length; i++) {
            final MediaCodecInfo codecInfo = infos[i];
            final JSONObject codec = new JSONObject();
            final String[] supportedTypes = codecInfo.getSupportedTypes();
            codec.put("name", codecInfo.getName())
                    .put("isEncoder", codecInfo.isEncoder());
            final JSONObject supportedTypesJson = new JSONObject();
            for (String type : supportedTypes) {
                supportedTypesJson.put(type, collectCapabilitiesForType(codecInfo, type));
            }
            codec.put("supportedTypes", supportedTypesJson);
            result.put(String.valueOf(i), codec);
        }
        return result;
    }
227850
public static Object beanClone(Object obj, Set<String> ignoreProperties) throws CloneNotSupportedException {

        final Class<?> clazz = obj.getClass();

        try {

            final Object clonedBean = clazz.newInstance();

            final List<PropertyDescriptor> propertyDescriptors = BeanIntrospector.getPropertyDescriptorsWithGettersAndSetters(clazz);
            for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {

                final String propertyName = propertyDescriptor.getName();

                final boolean ignoredProperty = ignoreProperties.contains(propertyName);

                if (!ignoredProperty) {

                    final Method getter = propertyDescriptor.getReadMethod();
                    final Method setter = propertyDescriptor.getWriteMethod();

                    Object value = getter.invoke(obj, NO_PARAMS);
                    if (value != null) {
                        value = doClone(value);
                        setter.invoke(clonedBean, new Object[] { value });
                    }

                }

            }

            return clonedBean;

        } catch (final CloneNotSupportedException e) {
            LOG.error("Error while cloning bean", e);
            throw e;
        } catch (final Exception e) {
            LOG.error("Error while cloning bean", e);
            throw new CloneNotSupportedException("Cannot clone a " + clazz + " object");
        }

    }
1239831
protected void checkJsonBeanValidator() {
        final Class<?> returnType = executeMethod.getReturnType();
        if (!JsonResponse.class.isAssignableFrom(returnType)) {
            return;
        }
        final Type genericReturnType = executeMethod.getGenericReturnType();
        if (genericReturnType == null || !(genericReturnType instanceof ParameterizedType)) { // just in case
            return;
        }
        final Class<?> jsonBeanType = DfReflectionUtil.getGenericFirstClass(genericReturnType);
        if (jsonBeanType == null) { // just in case
            return;
        }
        if (Collection.class.isAssignableFrom(jsonBeanType)) { // e.g. JsonResponse<List<SeaBean>>
            final Type[] resopnseArgTypes = DfReflectionUtil.getGenericParameterTypes(genericReturnType);
            if (resopnseArgTypes.length > 0) { // just in case
                final Class<?> elementBeanType = DfReflectionUtil.getGenericFirstClass(resopnseArgTypes[0]);
                if (elementBeanType != null && mayBeJsonBeanType(elementBeanType)) { // just in case
                    doCheckJsonBeanValidator(elementBeanType, Collections.emptyMap()); // can check JsonResponse<List<SeaBean>>
                }
            }
        } else if (mayBeJsonBeanType(jsonBeanType)) { // e.g. JsonResponse<SeaBean>, JsonResponse<WholeBean<SeaBean>>
            doCheckJsonBeanValidator(jsonBeanType, prepareJsonBeanGenericMap(genericReturnType, jsonBeanType));
        }
    }