<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>曾华水的博客 &#187; json</title>
	<atom:link href="http://www.mrzeng.com/tag/json/feed" rel="self" type="application/rss+xml" />
	<link>http://www.mrzeng.com</link>
	<description>NO.1 or Nothing</description>
	<lastBuildDate>Wed, 07 Sep 2011 12:47:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Json下的Positioned Update not supported解决方法</title>
		<link>http://www.mrzeng.com/post/json-positioned-update-not-supported.html</link>
		<comments>http://www.mrzeng.com/post/json-positioned-update-not-supported.html#comments</comments>
		<pubDate>Fri, 10 Jun 2011 05:03:08 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=275</guid>
		<description><![CDATA[今天使用json输出的时候报了这个错误，原因找了一下，发现使用hibernate自动生成的一些类会出现这个情况，主要是因为hibernate使用了延迟加载所造成的缘故。 因为我的系统前台使用的jquery-easeyui的dataGrid表格，所以，只能重新建一个类来进行。代码如下 package com.mrzeng.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.huashui.authentication.AuthName; import org.huashui.dto.PageBean; import org.huashui.service.IPaginate; import org.huashui.util.StringUtils; import org.huashui.util.WebUtils; import com.mrzeng.hibernate.Category; import com.mrzeng.hibernate.Crawlrecord; import com.mrzeng.hibernate.Saleinfo; import com.mrzeng.hibernate.Shop; import com.mrzeng.hibernate.Shopdetail; import com.mrzeng.service.IAnalysisService; /** * @fileName ShopdetailAction.java * @author 曾华水 [...]]]></description>
			<content:encoded><![CDATA[<div>今天使用json输出的时候报了这个错误，原因找了一下，发现使用hibernate自动生成的一些类会出现这个情况，主要是因为hibernate使用了延迟加载所造成的缘故。<br />
因为我的系统前台使用的jquery-easeyui的dataGrid表格，所以，只能重新建一个类来进行。代码如下
</div>
<pre class=prettyprint>
package com.mrzeng.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.huashui.authentication.AuthName;
import org.huashui.dto.PageBean;
import org.huashui.service.IPaginate;
import org.huashui.util.StringUtils;
import org.huashui.util.WebUtils;

import com.mrzeng.hibernate.Category;
import com.mrzeng.hibernate.Crawlrecord;
import com.mrzeng.hibernate.Saleinfo;
import com.mrzeng.hibernate.Shop;
import com.mrzeng.hibernate.Shopdetail;
import com.mrzeng.service.IAnalysisService;

/**
 * @fileName ShopdetailAction.java
 * @author  曾华水
 * @email zenghuashui@gmail.com
 * @date Jun 10, 2011
 * @time 9:07:13 AM
 * 代码类代码编写规约：add-增加，edit修改，remove删除，list列出全部，排除用ex，tree代表树
 */
@ParentPackage("huashui-default")
@Namespace("/admin")
@Results( {
		@Result(name = "saleinfo", location = "/WEB-INF/data/saleinfo.jsp"),
		@Result(name = "json", location = "/WEB-INF/view/json.jsp"),
		@Result(name = "jsonfilter", location = "/WEB-INF/view/jsonfilter.jsp"),
		@Result(name = "jsonfiltertype", location = "/WEB-INF/view/jsonfiltertype.jsp") })
public class SaleinfoAction {

	@Resource
	private IPaginate paginate;
	@Resource
	private IAnalysisService analysisService;
	private Integer rows;
	private Integer page;
	private Integer total;
	private String sort;
	private String order;

	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public Integer getRows() {
		return rows;
	}
	public void setRows(Integer rows) {
		this.rows = rows;
	}
	public Integer getPage() {
		return page;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	public Integer getTotal() {
		return total;
	}
	public void setTotal(Integer total) {
		this.total = total;
	}
	@Action("data_saleinfo")
	@AuthName("DATA_SALEINFO")
	public String index(){
		List<shop> shops = analysisService.listShop();
		List<crawlrecord> crawls = analysisService.listCrawlrecord();
		StringBuilder sb = new StringBuilder();
		for (Shop shop : shops) {
			if (!StringUtils.isNull(sb.toString())) {
				sb.append(",\r\n");
			}
			sb.append("{").append("id:").append(shop.getId()).append(
					",name:\"").append(shop.getName()).append(
					"\"}\r\n");
		}
		WebUtils.getRequest().setAttribute("shops", sb.toString());

		StringBuilder sb2 = new StringBuilder();
		for (Crawlrecord crawlrecord : crawls) {
			if (!StringUtils.isNull(sb2.toString())) {
				sb2.append(",\r\n");
			}
			sb2.append("{").append("id:").append(crawlrecord.getId()).append(
					",name:\"").append(StringUtils.dateToString(crawlrecord.getCrawltime(), "yyyy-MM-dd hh:mm:ss")).append(
					"\"}\r\n");
		}
		WebUtils.getRequest().setAttribute("crawls", sb2.toString());
		return "saleinfo";
	}
	@Action("data_saleinfo_list")
	@AuthName("DATA_SALEINFO")
	public String list(){
		Map<string , Object> data = new HashMap</string><string , Object>();
		StringBuilder sql = new StringBuilder();
		sql.append("from ").append(Saleinfo.class.getSimpleName());
		sql.append(" where 1=1");

		if (!StringUtils.isNull(sort) &#038;&#038; !StringUtils.isNull(order)) {
			if (order.trim().equalsIgnoreCase("desc")
					|| order.trim().equalsIgnoreCase("asc"))
				sql.append(" order by ").append(sort).append(" ").append(order);
		}
		PageBean pageBean = new PageBean();
		pageBean.setPage(page);
		pageBean.setPageSize(rows);

		pageBean.setListSQL(sql.toString());
		try {
			pageBean.setCount(paginate.getTotalCount(pageBean).intValue());
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<saleinfo> list = paginate.getList(pageBean);
		List<saleinfobean> rList = new ArrayList</saleinfobean><saleinfobean>();
		for (Saleinfo saleinfo : list) {
			SaleinfoBean bean = new SaleinfoBean();
			bean.setBuyer(saleinfo.getBuyer());
			bean.setBuyerCode(saleinfo.getBuyerCode());
			bean.setBuyerLevel(saleinfo.getBuyerLevel());
			bean.setBuyNum(saleinfo.getBuyNum());
			bean.setBuyTime(saleinfo.getBuyTime());
			bean.setCrawlId(saleinfo.getCrawlrecord().getId());
			bean.setGoodDesc(saleinfo.getGoodDesc());
			bean.setGoodPrice(saleinfo.getGoodPrice());
			bean.setGoodTitle(saleinfo.getGoodTitle());
			bean.setGoodUrl(saleinfo.getGoodUrl());
			bean.setId(saleinfo.getId());
			bean.setShopId(saleinfo.getShop().getId());
			rList.add(bean);
		}
		data.put("rows", rList);
		data.put("total", pageBean.getCount());

		WebUtils.getRequest().setAttribute("data", data);
		WebUtils.getRequest().setAttribute("type", "Set");
		return "jsonfiltertype";

	}

	public class SaleinfoBean{
		private Long id;
		private Integer shopId;
		private Long  crawlId;
		private Date buyTime;
		private Integer buyNum;
		private String buyer;
		private String buyerCode;
		private Integer buyerLevel;
		private String goodTitle;
		private String goodDesc;
		private Double goodPrice;
		private String goodUrl;
		public Long getId() {
			return id;
		}
		public void setId(Long id) {
			this.id = id;
		}
		public Integer getShopId() {
			return shopId;
		}
		public void setShopId(Integer shopId) {
			this.shopId = shopId;
		}
		public Long getCrawlId() {
			return crawlId;
		}
		public void setCrawlId(Long crawlId) {
			this.crawlId = crawlId;
		}
		public Date getBuyTime() {
			return buyTime;
		}
		public void setBuyTime(Date buyTime) {
			this.buyTime = buyTime;
		}
		public Integer getBuyNum() {
			return buyNum;
		}
		public void setBuyNum(Integer buyNum) {
			this.buyNum = buyNum;
		}
		public String getBuyer() {
			return buyer;
		}
		public void setBuyer(String buyer) {
			this.buyer = buyer;
		}
		public String getBuyerCode() {
			return buyerCode;
		}
		public void setBuyerCode(String buyerCode) {
			this.buyerCode = buyerCode;
		}
		public Integer getBuyerLevel() {
			return buyerLevel;
		}
		public void setBuyerLevel(Integer buyerLevel) {
			this.buyerLevel = buyerLevel;
		}
		public String getGoodTitle() {
			return goodTitle;
		}
		public void setGoodTitle(String goodTitle) {
			this.goodTitle = goodTitle;
		}
		public String getGoodDesc() {
			return goodDesc;
		}
		public void setGoodDesc(String goodDesc) {
			this.goodDesc = goodDesc;
		}
		public Double getGoodPrice() {
			return goodPrice;
		}
		public void setGoodPrice(Double goodPrice) {
			this.goodPrice = goodPrice;
		}
		public String getGoodUrl() {
			return goodUrl;
		}
		public void setGoodUrl(String goodUrl) {
			this.goodUrl = goodUrl;
		}

	}
}

</saleinfobean></saleinfo></string></crawlrecord></shop></pre>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/json-utils.html" title="Json工具类">Json工具类</a><br /><small>jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。

代码如下：

@SuppressWarnings("unchecked")
public class JsonUtils {

	

	/**
	 * 从一个JSON 对象字符...</small></li><li><a href="http://www.mrzeng.com/post/sql-server-jdbc.html" title="SQL Server的JDBC驱动问题">SQL Server的JDBC驱动问题</a><br /><small>最近公司换服务器把数据库从SQL Server 2005 升级到 SQL Server 2008。这样，以这个数据库对接的两个系统全部瘫痪，无法进行数据库对接。
首先立即判断是是数据库的驱动问题，好不容易从网上找到了了驱动，下载下来，发现里面有两个文件一个是sqljdbc.jar，另外一个是sqljdbc4.jar,于是将驱动换掉，两个全部导进去，加到CLASSPATH路径，发现，还是不行。两个...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/json-positioned-update-not-supported.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Json工具类</title>
		<link>http://www.mrzeng.com/post/json-utils.html</link>
		<comments>http://www.mrzeng.com/post/json-utils.html#comments</comments>
		<pubDate>Wed, 03 Mar 2010 08:06:40 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=155</guid>
		<description><![CDATA[jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。 代码如下： @SuppressWarnings("unchecked") public class JsonUtils { /** * 从一个JSON 对象字符格式中得到一个java对象，形如： * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}} * @param object * @param clazz * @return */ public static Object getDTO(String jsonString, Class clazz) { JSONObject jsonObject = null; try { setDataFormat2JAVA(); jsonObject = JSONObject.fromObject(jsonString); } catch (Exception e) [...]]]></description>
			<content:encoded><![CDATA[<p>jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。<br />
<span id="more-155"></span><br />
代码如下：</p>
<pre class=prettyprint>
@SuppressWarnings("unchecked")
public class JsonUtils {

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，形如：
	 * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}}
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz) {
		JSONObject jsonObject = null;
		try {
			setDataFormat2JAVA();
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject, clazz);
	}

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，其中beansList是一类的集合，形如：
	 * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...},
	 * beansList:[{}, {}, ...]}
	 * @param jsonString
	 * @param clazz
	 * @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class)
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz, Map map) {
		JSONObject jsonObject = null;
		try {
			setDataFormat2JAVA();
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject, clazz, map);
	}

	/**
	 * 从一个JSON数组得到一个java对象数组，形如：
	 * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object[] getDTOArray(String jsonString, Class clazz) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i &lt; array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz);
		}
		return obj;
	}

	/**
	 * 从一个JSON数组得到一个java对象数组，形如：
	 * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
	 * @param object
	 * @param clazz
	 * @param map
	 * @return
	 */
	public static Object[] getDTOArray(String jsonString, Class clazz, Map map) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i &lt; array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz, map);
		}
		return obj;
	}

	/**
	 * 从一个JSON数组得到一个java对象集合
	 * @param object
	 * @param clazz
	 * @return
	 */

	public static List getDTOList(String jsonString, Class clazz) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}

	/**
	 * 从一个JSON数组得到一个java对象集合，其中对象中包含有集合属性
	 * @param object
	 * @param clazz
	 * @param map 集合属性的类型
	 * @return
	 * class MyBean{
	 *   private List data;
	 *		   // getters &#038; setters
	 *	}
	 *
	 * class Person{
	 *	   private String name;
	 *	   // getters &#038; setters
	 *	}
	 *
	 *	...
	 *
	 *	String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";
	 *  Map classMap = new HashMap();
	 *	classMap.put( "data", Person.class );
	 *	MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );
	 */
	public static List getDTOList(String jsonString, Class clazz, Map map) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz, map));
		}
		return list;
	}

	/**
	 * 从json HASH表达式中获取一个map，该map支持嵌套功能
	 * 形如：{"id" : "johncon", "name" : "小强"}
	 * 注意commons-collections版本，必须包含org.apache.commons.collections.map.MultiKeyMap
	 * @param object
	 * @return
	 */
	public static Map getMapFromJson(String jsonString) {
		setDataFormat2JAVA();
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, jsonObject.get(key));
		}
		return map;
	}

	/**
	 * 从json数组中得到相应java数组
	 * json形如：["123", "456"]
	 * @param jsonString
	 * @return
	 */
	public static Object[] getObjectArrayFromJson(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		return jsonArray.toArray();
	}

	/**
	 * 把数据对象转换成json字符串
	 * DTO对象形如：{"id" : idValue, "name" : nameValue, ...}
	 * 数组对象形如：[{}, {}, {}, ...]
	 * map对象形如：{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...}
	 * @param object
	 * @return
	 */
	public static String getJSONString(Object object) throws Exception {
		String jsonString = null;
		//日期值处理器
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new JsonDateValueProcessor());
		if (object != null) {
			if (object instanceof Collection || object instanceof Object[]) {
				jsonString = JSONArray.fromObject(object, jsonConfig)
						.toString();
			} else {
				jsonString = JSONObject.fromObject(object, jsonConfig)
						.toString();
			}
		}
		return jsonString == null ? "{}" : jsonString;
	}

	private static void setDataFormat2JAVA() {
		//设定日期转换格式
		JSONUtils.getMorpherRegistry().registerMorpher(
				new DateMorpher(new String[] { "yyyy-MM-dd",
						"yyyy-MM-dd HH:mm:ss" }));
	}

	public static void main(String[] arg) throws Exception {
		String s = "{status : 'success'}";
		System.out.println(" object : " + JsonUtils.getJSONString(s));
	}
}
</pre>
<p></code>
<pre class=prettyprint>
public class JsonDateValueProcessor implements JsonValueProcessor {

	private String format = "yyyy-MM-dd HH:mm:ss";

	public JsonDateValueProcessor() {

	}

	public JsonDateValueProcessor(String format) {
		this.format = format;
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	private Object process( Object value, JsonConfig jsonConfig ) {
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value == null ? null : value.toString();
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

}
</pre>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/json-positioned-update-not-supported.html" title="Json下的Positioned Update not supported解决方法">Json下的Positioned Update not supported解决方法</a><br /><small>今天使用json输出的时候报了这个错误，原因找了一下，发现使用hibernate自动生成的一些类会出现这个情况，主要是因为hibernate使用了延迟加载所造成的缘故。
因为我的系统前台使用的jquery-easeyui的dataGrid表格，所以，只能重新建一个类来进行。代码如下


package com.mrzeng.action;

import java.util.Array...</small></li><li><a href="http://www.mrzeng.com/post/sql-server-jdbc.html" title="SQL Server的JDBC驱动问题">SQL Server的JDBC驱动问题</a><br /><small>最近公司换服务器把数据库从SQL Server 2005 升级到 SQL Server 2008。这样，以这个数据库对接的两个系统全部瘫痪，无法进行数据库对接。
首先立即判断是是数据库的驱动问题，好不容易从网上找到了了驱动，下载下来，发现里面有两个文件一个是sqljdbc.jar，另外一个是sqljdbc4.jar,于是将驱动换掉，两个全部导进去，加到CLASSPATH路径，发现，还是不行。两个...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/json-utils.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

