com.iqiny.silly.common.util.SillyObjectUtil Maven / Gradle / Ivy
/*
* Copyright iqiny.com
*
* https://gitee.com/iqiny/silly
*
* project name:silly-common
* project description:top silly project pom.xml file
*/
package com.iqiny.silly.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.iqiny.silly.common.exception.SillyCheckException;
/**
* 傻瓜对象工具
*/
public abstract class SillyObjectUtil {
public static T toObject(String str, Class t) {
if (str == null || str.isEmpty()) {
return null;
}
if (str.startsWith("{") || str.startsWith("[")) {
return jsonToObject(str, t);
} else {
return yamlToObject(str, t);
}
}
public static T yamlToObject(String str, Class t) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
try {
return mapper.readValue(str, t);
} catch (JsonProcessingException e) {
throw new SillyCheckException(e.getMessage(), e);
}
}
public static T jsonToObject(String json, Class t) {
try {
return JSON.parseObject(json, t, Feature.OrderedField);
} catch (JSONException e) {
throw new SillyCheckException(e.getMessage(), e);
}
}
public static String objectToJsonString(Object obj) {
try {
return JSONObject.toJSONString(obj);
} catch (JSONException e) {
throw new SillyCheckException(e.getMessage(), e);
}
}
}