SSH中json数据的封装与easyui里json的显示

以前使用php的时候发现json的构造解析非常简单,但是呢,后来使用java的时候却发现java中要稍微复杂一点,所以呢在这里写一下我的实现方法

首先我是在这下面建了一个工具包,专门用来构造json的,代码

package com.test.tools;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.http.HttpServletResponse;

 

import com.google.gson.Gson;

 

publicclassJSONUtils {

   publicstaticvoidtoJson(HttpServletResponse response, Object data)

        throws IOException {

        Gson gson = new Gson();

        String result = gson.toJson(data);

        response.setContentType("text/json; charset=utf-8");

        response.setHeader("Cache-Control","no-cache"); //取消浏览器缓存

        PrintWriter out = response.getWriter();

        out.print(result);

        out.flush();

        out.close();

   }

}


这里使用的Gson,所以要报错,在lib中引用gson

这里的gson包需要自己下载,然后引入,版本不一定是2.2.1

Action中的实现

首先引入工具包

import com.test.tools.JSONUtils;

public String test() throws Exception{
        this.testList = UserDao.QueryAll("from User");
        JSONUtils.toJson(ServletActionContext.getResponse(), userList);
        return SUCCESS;    
    }


Struts.xml配置

<package name="struts" namespace="/" extends="struts-default,json-default">
        
        <action name="index" class="com.test.action.UserAction" method="test">
            <result type="json"><param name="root">jsonResult</param></result>
        </action>
        </package>

index.jsp

<table class="easyui-datagrid" title="UserInfo" style="width:100%;min-height:50px;"
data-options="singleSelect:true,collapsible:true,url:'index.action'">
<thead>
<tr>
<th data-options="field:'id',width:400">ID</th>
<th data-options="field:'username',width:400">username</th>
<th data-options="field:'userpwd',width:400">userpwd</th>
</tr>
</thead>
</table>

ok,现在信息就可以显示了!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值