代码:
。。。。。。1
try {
if (Map.class.isAssignableFrom(beanClass)) {
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)) {
Class targetClass = findTargetClass(key, classMap);
targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
JsonConfig jsc = jsonConfig.copy();
jsc.setRootClass(targetClass);
jsc.setClassMap(classMap);
if (targetClass != null) {
setProperty(bean, key, toBean((JSONObject)value, jsc), jsonConfig);
} else {
setProperty(bean, key, toBean((JSONObject)value), jsonConfig);
}
} else if (jsonConfig.isHandleJettisonEmptyElement() && “”.equals(value)) {
setProperty(bean, key, (Object)null, jsonConfig);
} else {
setProperty(bean, key, value, jsonConfig);
。。。。。。。2
private static void setProperty(Object bean, String key, Object value, JsonConfig jsonConfig) throws Exception {
PropertySetStrategy propertySetStrategy = jsonConfig.getPropertySetStrategy() != null ? jsonConfig.getPropertySetStrategy() : PropertySetStrategy.DEFAULT;
propertySetStrategy.setProperty(bean, key, value);
}
}
。。。。。。。。3
public void setProperty(Object bean, String key, Object value) throws JSONException {
if (bean instanceof Map) {
((Map)bean).put(key, value);
} else {
try {
PropertyUtils.setSimpleProperty(bean, key, value);
//缺少字段抛异常
//缺少字段抛异常
//缺少字段抛异常
} catch (Exception var5) {
throw new JSONException(var5);
}
}
}
解决:1
去掉不需要的字段
JsonConfig config = new JsonConfig();
config.setIgnoreDefaultExcludes(false);
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
config.setExcludes(new String[]{//只要设置这个数组,指定过滤哪些字段。
// “l2Interfaces”,
// “OSInstalled”,
“ipInterfaces”,
“OSRunning”,
“fileSystems”,
“balanceMan”,
“endStation”
});
//如果不需要过滤,方法可用fromObject(o)
JSONObject jsonObject = JSONObject.fromObject(o,config);
tt = (TT)JSONObject.toBean(jsonObject, TT.class);
解决:2
重新封装包装类,将异常封装
public class PropertyStrategyWrapper extends PropertySetStrategy {
private PropertySetStrategy original;
public PropertyStrategyWrapper(PropertySetStrategy original) {
this.original = original;
}
@Override
public void setProperty(Object o, String string, Object o1) throws JSONException {
try {
original.setProperty(o, string, o1);
} catch (Exception ex) {
//ignore
}
}
}
JsonConfig cfg = new JsonConfig();
// 设置属性包装器
cfg.setPropertySetStrategy(new PropertyStrategyWrapper(PropertySetStrategy.DEFAULT));
// 设置要转换成的JavaBean
cfg.setRootClass(TT.class);
// 转换
tt = (TT)JSONObject.toBean(obj, cfg);
https://blog.youkuaiyun.com/weixin_33866037/article/details/92383943