67,549
社区成员




public void testQueryNoXml() {
Session session = HibernateSessionFactory.getSession();
JSONArray array = new JSONArray();
try {
List list = session
.createSQLQuery(
"select cardid,cardreaderid,mapid,stayinterval from v_locatedata")
.setFirstResult(0)
.setMaxResults(10)
.list();
for (int i = 0; i < list.size(); i++) {
Object[] obj = (Object[]) list.get(i);
JSONObject row = new JSONObject();
row.put("cid", obj[0]);
row.put("crid", obj[1]);
row.put("mid", obj[2]);
row.put("stl", obj[3]);
array.add(row);
}
JSONObject json = new JSONObject();
json.put("rowcount", list.size());
json.put("rows", array);
System.out.println("sb.tostring: " + json);
} catch (RuntimeException re) {
log.error("==converse json failed==", re);
} finally {
session.close();
}
}
import java.lang.reflect.*;
import java.util.*;
class ListToJson{
public static void main(String[] args) throws Exception
{
// System.out.println(Class.forName("ttt").getDeclaredFields()[0].getModifiers());
List list=new ArrayList();
list.add(new ttt());
list.add(new ttt());
list.add(new ttt());
toJson(list);
}
public static String toJson(List list) throws Exception
{
StringBuffer result=new StringBuffer();
if(list==null && list.size()==0)
{
return result.toString();
}
Object obj=list.get(0);
Method[] method=obj.getClass().getDeclaredMethods();
result.append("[");
for(int i=0;i<list.size();i++)
{
obj=list.get(i);
result.append("{");
for(int j=0;j<method.length;j++)
{
if(method[j].getName().startsWith("get"))
{
result.append(toFieldName(method[j].getName()));
result.append(":");
result.append(method[j].invoke(obj));
result.append(",");
}
}
result.deleteCharAt(result.length()-1);
result.append("}");
}
result.append("]");
System.out.println(result.toString());
return result.toString();
}
public static String toFieldName(String methodName)
{
String result="";
result+=(char)(methodName.charAt(3)+32);
for(int i=4;i<methodName.length();i++)
{
result+=methodName.charAt(i);
}
return result;
}
}
class ttt
{
public String a="tt";
private int b;
public String getA() {
return a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public void setA(String a) {
this.a = a;
}
}