项目中用到,写个demo方便copy
1、首先说明一点,json-lib 需要支持包
?
Json-lib requires (at least) the following dependencies in your classpath:
- jakarta commons-lang 2.5
- jakarta commons-beanutils 1.8.0
- jakarta commons-collections 3.2.1
- jakarta commons-logging 1.1.1
- ezmorph 1.0.6
上述都可以在http://json-lib.sourceforge.net/ 下得到
?
解析第一种格式,因为前台是使用jstl,所以后台处理就全部转换成JavaBean了,方便使用。
其中JavaBean必须为public的才ok,否则会报找不到setter 和 getter 方法,比较纠结。
/** * java Bean * @author wuya * */ public class GgDw { private String dwbh; private String dwmc; public String getDwbh() { return dwbh; } public void setDwbh(String dwbh) { this.dwbh = dwbh; } public String getDwmc() { return dwmc; } public void setDwmc(String dwmc) { this.dwmc = dwmc; } }
?testcase 这里可以不看,上篇有个拼接json数据格式的方法需要用到
public class DBTest extends TestCase { DBUtil db = new DBUtil(); Connection con = null; Statement stmt = null; ResultSet rs = null; JsonUtil json = new JsonUtil(); public void testGetConnect() throws SQLException { con = db.getConnect(); stmt = con.createStatement(); rs = stmt.executeQuery("select dwbh,dwmc from gg_dw where dwbh<5"); String str = json.GetJsonByResultSet(rs, "result", 1); System.out.println(str); assertNotNull(str); } public void testJsonStringToBean() throws SQLException { con = db.getConnect(); stmt = con.createStatement(); rs = stmt.executeQuery("select dwbh,dwmc from gg_dw where dwbh<5"); // String str = json.GetJsonByResultSet(rs, "result", 1); String str1 = json.GetJsonByResultSet(rs, "result", 0); System.out.println(str1); // JsonLibParse.jsonStringToBeanMap(str); JsonLibParse.jsonStringToBeanArray(str1); } }
?解析使用json-lib 注意 GgDw必须为public class
* json格式的sring 解析 * {result:[ {dwbh:"1",dwmc:"有限公司"}]} * @param jsonString */ public static void jsonStringToBeanMap(String jsonString) { Map classMap = new HashMap(); classMap.put("result", GgDw.class); Result result = (Result) JSONObject.toBean(JSONObject .fromObject(jsonString), Result.class, classMap); for (Object o : result.getResult()) { System.out.println(((GgDw) o).getDwbh()); System.out.println(((GgDw) o).getDwmc()); } }
?这个是转换包含Array形式的数据格式
// {result:[ // {id:0,data:["","1","有限公司1"]}, // {id:1,data:["","2","有限公司2"]}, // {id:2,data:["","3","有限公司3"]}, // {id:3,data:["","4","有限公司4"]} // ]} public static void jsonStringToBeanArray(String jsonString) { JSONObject js = JSONObject.fromObject(jsonString); JSONArray jsonArray = js.getJSONArray("result"); for(int i=0;i<jsonArray.size();i++){ JSONObject json = jsonArray.getJSONObject(i); System.out.println(jsonArray.getJSONObject(i).getString("id")); String temp = jsonArray.getJSONObject(i).getString("data"); JSONArray js1 = JSONArray.fromObject(temp); for (Object string : js1.toArray()) { System.out.println(string); } } }
?项目中就可以简单使用了,完全满足项目使用要求。