org.zbus.kit.JsonKit Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zbus Show documentation
Show all versions of zbus Show documentation
lightweight message queue, service bus
package org.zbus.kit;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class JsonKit {
private static Method fastjsonMethod;
static{
try {
Class> fastjon = Class.forName("com.alibaba.fastjson.JSON");
fastjsonMethod = fastjon.getMethod("toJSONString", Object.class);
} catch (Exception e) {
//ignore
}
}
public static String toJson(Object value) {
if(fastjsonMethod != null){
try {
return (String)fastjsonMethod.invoke(null, value);
} catch (Exception e) {
e.printStackTrace();
}
}
return JsonWriter.toJson(value);
}
public static void main(String[] args){
System.out.println(JsonKit.toJson("xx"));
}
}
class JsonWriter {
public static String TimestampPattern = "yyyy-MM-dd HH:mm:ss";
public static String DatePattern = "yyyy-MM-dd";
@SuppressWarnings("unchecked")
public static String toJson(Object value) {
if(value == null) return "null";
if(value instanceof String)
return "\"" + escape((String)value) + "\"";
if(value instanceof Double){
if(((Double)value).isInfinite() || ((Double)value).isNaN())
return "null";
else
return value.toString();
}
if(value instanceof Float){
if(((Float)value).isInfinite() || ((Float)value).isNaN())
return "null";
else
return value.toString();
}
if(value instanceof Number)
return value.toString();
if(value instanceof Boolean)
return value.toString();
if (value instanceof java.util.Date) {
if (value instanceof java.sql.Timestamp)
return "\"" + new SimpleDateFormat(TimestampPattern).format(value) + "\"";
if (value instanceof java.sql.Time)
return "\"" + value.toString() + "\"";
return "\"" + new SimpleDateFormat(DatePattern).format(value) + "\"";
}
if(value instanceof Map) {
return mapToJson((Map
© 2015 - 2025 Weber Informatics LLC | Privacy Policy