📄 jsonutils.java
字号:
package anni.json;
import java.io.PrintWriter;
import java.lang.reflect.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public class JsonUtils {
private String inputDatePattern = "";
private String outputDatePattern = "";
public JsonUtils() {
this("yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss");
}
public JsonUtils(String inputDatePattern, String outputDatePattern) {
this.inputDatePattern = inputDatePattern;
this.outputDatePattern = outputDatePattern;
}
public <T> T json2Bean(String data, Class<T> clazz) {
try {
return json2Bean(data, clazz.newInstance());
} catch (Exception ex) {
System.err.println(ex);
return null;
}
}
public <T> T json2Bean(JsonObject jsonObject, Class<T> clazz) {
try {
return json2Bean(jsonObject, clazz.newInstance());
} catch (Exception ex) {
System.err.println(ex);
return null;
}
}
public <T> T json2Bean(String data, T bean) {
Json json = this.parse(data);
if (json instanceof JsonObject) {
JsonObject jsonObject = (JsonObject) json;
return json2Bean(jsonObject, bean);
}
return bean;
}
public <T> T json2Bean(JsonObject jsonObject, T bean) {
for (Method m : bean.getClass().getDeclaredMethods()) {
String name = m.getName();
Class[] types = m.getParameterTypes();
try {
if (name.startsWith("set") && (types.length == 1)) {
Class type = types[0];
if (type.equals(byte.class) || type.equals(Byte.class)) {
byte value = jsonObject.getByte(m2f(name));
m.invoke(bean, value);
} else if (type.equals(short.class)
|| type.equals(Short.class)) {
short value = jsonObject.getShort(m2f(name));
m.invoke(bean, value);
} else if (type.equals(int.class)
|| type.equals(Integer.class)) {
int value = jsonObject.getInt(m2f(name));
m.invoke(bean, value);
} else if (type.equals(long.class)
|| type.equals(Long.class)) {
long value = jsonObject.getLong(m2f(name));
m.invoke(bean, value);
} else if (type.equals(float.class)
|| type.equals(Float.class)) {
float value = jsonObject.getFloat(m2f(name));
m.invoke(bean, value);
} else if (type.equals(double.class)
|| type.equals(Double.class)) {
double value = jsonObject.getDouble(m2f(name));
m.invoke(bean, value);
} else if (type.equals(char.class)
|| type.equals(Character.class)) {
char value = jsonObject.getChar(m2f(name));
m.invoke(bean, value);
} else if (type.equals(boolean.class)
|| type.equals(Boolean.class)) {
boolean value = jsonObject.getBoolean(m2f(name));
m.invoke(bean, value);
} else if (type.equals(String.class)) {
String value = jsonObject.getString(m2f(name));
m.invoke(bean, value);
} else if (type.equals(Date.class)) {
Date value = jsonObject.getDate(m2f(name));
m.invoke(bean, value);
}
}
} catch (Exception ex) {
System.err.println(ex);
}
}
return bean;
}
public <T> List<T> json2Array(String data, Class<T> clazz) {
Json json = this.parse(data);
List<T> list = new ArrayList<T>();
if (json instanceof JsonArray) {
for (Json item : (JsonArray) json) {
if (item instanceof JsonObject) {
JsonObject jsonObject = (JsonObject) item;
list.add(json2Bean(jsonObject, clazz));
}
}
} else {
return list;
}
return list;
}
private String m2f(String methodName) {
String fieldName = methodName.substring(3, 4).toLowerCase()
+ methodName.substring(4);
return fieldName;
}
public String bean2Json(Object bean) {
if (bean instanceof Collection) {
return bean2JsonArray((Collection) bean);
} else {
return bean2JsonObject(bean);
}
}
public void write(Object bean, PrintWriter out) {
out.print(bean2Json(bean));
out.flush();
}
private String bean2JsonArray(Collection collection) {
StringBuffer buff = new StringBuffer();
buff.append("[");
for (Object o : collection) {
if (o instanceof Collection) {
buff.append(bean2JsonArray((Collection) o));
} else {
buff.append(bean2JsonObject(o));
}
buff.append(",");
}
if (buff.length() > 1) {
buff.deleteCharAt(buff.length() - 1);
}
buff.append("]");
return buff.toString();
}
private String bean2JsonObject(Object o) {
if (o == null) {
return null;
}
StringBuffer buff = new StringBuffer();
buff.append("{");
Class clazz = o.getClass();
if (clazz.equals(String.class)) {
return "\"" + formatString(o) + "\"";
} else if (isNumOrBool(clazz)) {
return o.toString();
} else {
for (Method m : clazz.getDeclaredMethods()) {
String name = m.getName();
Class[] types = m.getParameterTypes();
if (name.startsWith("get") && (types.length == 0)) {
buff.append("\"").append(m2f(name)).append("\":");
try {
Object returnValue = m.invoke(o, null);
Class type = m.getReturnType();
if (returnValue == null) {
buff.append("null");
} else if (isNumOrBool(type)) {
buff.append(returnValue.toString());
} else if (returnValue instanceof Collection) {
buff.append(bean2JsonArray(
(Collection) returnValue));
} else if (type.equals(String.class)) {
buff.append("\"")
.append(formatString(returnValue))
.append("\"");
} else if (type.equals(Date.class)) {
buff.append("\"")
.append(new SimpleDateFormat(
outputDatePattern).format(
(Date) returnValue)).append("\"");
} else {
buff.append(bean2JsonObject(returnValue));
}
} catch (Exception ex) {
System.err.println(ex);
buff.append("null");
}
buff.append(",");
}
}
}
if (buff.length() > 1) {
buff.deleteCharAt(buff.length() - 1);
}
buff.append("}");
return buff.toString();
}
private String formatString(Object obj) {
if (obj == null) {
return "null";
} else {
return obj.toString().replaceAll("\\\\", "\\\\\\\\")
.replaceAll("'", "\\\\'").replaceAll("\\\"", "\\\\\"");
}
}
private boolean isNumOrBool(Class clazz) {
return isNumber(clazz) || isBoolean(clazz);
}
private boolean isNumber(Class type) {
return type.equals(byte.class) || type.equals(Byte.class)
|| type.equals(short.class) || type.equals(Short.class)
|| type.equals(int.class) || type.equals(Integer.class)
|| type.equals(long.class) || type.equals(Long.class)
|| type.equals(float.class) || type.equals(Float.class)
|| type.equals(double.class) || type.equals(Double.class);
}
private boolean isBoolean(Class type) {
return type.equals(boolean.class) || type.equals(Boolean.class);
}
// ====================================================
// parse
public Json parse(String data) {
String value = data.trim();
char c = value.charAt(0);
if (c == '{') {
return parseObject(value, 0);
} else if (c == '[') {
return parseArray(value, 0);
}
return null;
}
public JsonObject parseObject(String data, int start) {
//
JsonObject jsonObject = null;
boolean isKey = true;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -