您的位置:首页 > 编程语言 > Java开发

Java类,生成Dojo_Gird表格的json数据格式

2012-03-26 00:28 465 查看
修改了前段时间的生成json格式的类,与Dojo grid完美结合。通过ajax获取此json数据,再赋予grid的store里。

public class MyJson {
private String json;
private String js;
private String header;
private String ident;
privateintisfirst = 0;
public MyJson(String id)
{
json = "\"items\":[";
js = "{";
ident = id;
}
public String getjson()
{
json = json + "]}";
json = header + json;
if(json.substring(0, 4).equals("null")) json = "{\"identifier\":\""+ident+"\",\"isempty\":\"true\",\"count\":\"1\",\"items\":[{\""+ident+"\":\"未查到相关信息\"}]}";
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)
{
if(map.isEmpty()) return;
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);
if(isfirst==0)
{
header = "{\"identifier\":\""+ident+"\",";
}
}
endjs();
isfirst++;
}
publicvoid addrec()
{
if(isfirst!=1) json = json + ",";
json = json + js;
js = "{";
}
publicvoid setextra(String name,String value)
{
header = header + "\""+name+"\":\"" + value + "\",";
}
public String showJson(){
returnjson;
}
public String getEmpty(){
return"{\"identifier\":\""+ident+"\",\"isempty\":\"true\",\"items\":[{\""+ident+"\":\"未查到相关信息\"}]}";
}
}


调用:

MyJson json = new MyJson("id");  //初始化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中
}
json.setextra("total",num); //可插入附加信息
String text = json.getjson();  //获得json格式字符串
out.println(text);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: