use of com.dtflys.forest.exceptions.ForestConvertException in project forest by dromara.
the class ForestJaxbConverter method encodeToString.
@Override
public String encodeToString(Object obj) {
if (obj == null) {
return null;
}
if (obj instanceof CharSequence) {
return obj.toString();
}
if (obj instanceof Map || obj instanceof List) {
throw new ForestRuntimeException("[Forest] JAXB XML converter dose not support translating instance of java.util.Map or java.util.List");
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
StringWriter writer = new StringWriter();
createMarshaller(jaxbContext, "UTF-8").marshal(obj, writer);
return writer.toString();
} catch (JAXBException e) {
throw new ForestConvertException(this, e);
}
}
use of com.dtflys.forest.exceptions.ForestConvertException in project forest by dromara.
the class DefaultAutoConverter method convertToJavaObject.
@Override
public <T> T convertToJavaObject(Object source, Type targetType) {
if (source == null) {
return null;
}
if (source instanceof InputStream || source instanceof byte[] || source instanceof File) {
if (canReadAsBinary(targetType)) {
return tryConvert(source, targetType, ForestDataType.BINARY);
}
if (protobufConverterManager.isProtobufMessageType(targetType)) {
return tryConvert(source, targetType, ForestDataType.PROTOBUF);
}
source = readAsString(source);
}
T result = null;
Class clazz = ReflectUtils.toClass(targetType);
if (source instanceof CharSequence) {
String str = source.toString();
if (String.class.isAssignableFrom(clazz)) {
return (T) str;
}
String trimmedStr = str.trim();
if (trimmedStr.length() == 0) {
if (CharSequence.class.isAssignableFrom(clazz)) {
return tryConvert(str, targetType, ForestDataType.TEXT);
}
return null;
}
char ch = trimmedStr.charAt(0);
try {
if (ch == '{' || ch == '[') {
result = tryConvert(trimmedStr, targetType, ForestDataType.JSON);
} else if (ch == '<') {
result = tryConvert(trimmedStr, targetType, ForestDataType.XML);
} else if (Character.isDigit(ch)) {
try {
result = tryConvert(trimmedStr, targetType, ForestDataType.JSON);
} catch (Throwable th) {
result = tryConvert(source, targetType, ForestDataType.TEXT);
}
} else if ("true".equalsIgnoreCase(trimmedStr)) {
if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) {
result = (T) Boolean.TRUE;
} else {
result = tryConvert(trimmedStr, targetType, ForestDataType.TEXT);
}
} else if ("false".equalsIgnoreCase(trimmedStr)) {
if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) {
result = (T) Boolean.FALSE;
} else {
result = tryConvert(trimmedStr, targetType, ForestDataType.TEXT);
}
} else {
result = tryConvert(source, targetType, ForestDataType.TEXT);
}
} catch (Throwable th) {
throw new ForestConvertException(this, th);
}
}
return result;
}
Aggregations