package com.tuxin.tool.json;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class JSON
{
public static String encode(Object obj)
{
if ((obj == null) || (obj.toString().equals("null"))) return "";
if ((obj != null) && (obj.getClass() == String.class)) {
return obj.toString();
}
JSONSerializer serializer = new JSONSerializer();
serializer.transform(new DateTransformer("yyyy-MM-dd' 'HH:mm:ss"), new Class[] { Date.class });
serializer.transform(new DateTransformer("yyyy-MM-dd' 'HH:mm:ss"), new Class[] { Timestamp.class });
String json = serializer.deepSerialize(obj);
return json;
}
public static Object recode(String json) {
if (StringUtil.isNullOrEmpty(json)) return "";
JSONDeserializer deserializer = new JSONDeserializer();
deserializer.use(String.class, new DateTransformer("yyyy-MM-dd' 'HH:mm:ss"));
Object obj = deserializer.deserialize(json);
if ((obj != null) && (obj.getClass() == String.class)) {
return recode(obj.toString());
}
return obj;
}
public static Map toMap(Object javaBean)
{
Map result = new HashMap();
Method[] methods = javaBean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("get")) {
String field = method.getName();
field = field.substring(field.indexOf("get") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
Object value = method.invoke(javaBean, null);
result.put(field, value == null ? "" : value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static Map toMap(String jsonString)
throws JSONException
{
JSONObject jsonObject = new JSONObject(jsonString);
Map result = new HashMap();
Iterator iterator = jsonObject.keys();
String key = null;
String value = null;
while (iterator.hasNext())
{
key = (String)iterator.next();
value = jsonObject.getString(key);
result.put(key, value);
}
return result;
}
public static JSONObject toJSON(Object bean)
{
return new JSONObject(toMap(bean));
}
public static Object toJavaBean(Object javabean, Map data)
{
Method[] methods = javabean.getClass().getDeclaredMethods();
for (Method method : methods) {
try
{
if (method.getName().startsWith("set"))
{
String field = method.getName();
field = field.substring(field.indexOf("set") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
method.invoke(javabean, new Object[] {
data.get(field) });
}
}
catch (Exception localException)
{
}
}
return javabean;
}
public static void toJavaBean(Object javabean, String jsonString)
throws ParseException, JSONException
{
JSONObject jsonObject = new JSONObject(jsonString);
Map map = toMap(jsonObject.toString());
toJavaBean(javabean, map);
}
}