因为是想把hibernate获取的数据记录转换为json数据,网上的转json格式的java包无法识别记录中有外键的情形。于是决定自己写一个简单的用map转json格式字符串的类。
public class MyJson {
private String json;
private String js;
privateintisfirst = 0;
public MyJson()
{
json = "{\"json\":[";
js = "{";
}
public MyJson(String name)
{
json = "{\""+name+"\":[";
js = "{";
}
public String getjson()
{
json = json + "]}";
returnjson;
}
privatevoid endjs()
{
js = js.substring(0,js.length()-1);
js = js + "}";
}
privatevoid addcol(String name,String value)
{
js = js + "\"" + name +"\":" + "\"" + value + "\",";
}
publicvoid addmap(HashMap<String,String> map)
{
Iterator it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry m=(Map.Entry)it.next();
String name = m.getKey().toString();
String value = "-";
try{
value = m.getValue().toString();
}catch(Exception e)
{
value = "-";
}
addcol(name,value);
}
endjs();
isfirst++;
}
publicvoid addrec()
{
if(isfirst!=1) json = json + ",";
json = json + js;
js = "{";
}
}
调用:
MyJson json = new MyJson(“info”); //初始化json,参数为json数据第一字段。
for(int i=0;i<10;i++) //循环插入10组记录
{
//手动生成map格式记录
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("username","user0"+i);
hmap.put("userpass","pass0"+i);
json.addmap(hmap); //把map加入json中
json.addrec(); //更新记录到json中
}
String text = json.getjson(); //获得json格式字符串
out.println(text);
Ajax中调用:
ajax中传来参数后直接:
info[i].username