exception(gson)

GsonBuilder gb=new GsonBuilder() ; 

gb.excludeFieldsWithoutExposeAnnotation();

        Gson gson = gb.create();

userList = userService.findAll();

userJson=gson.toJson(userList);

getResponse().setContentType("application/json,charset=UTF-8");

PrintWriterout=getResponse().getWriter();

out.print(userJson);

out.flush();

        out.close();

最后只用@Expose序列化需要的pojo实体类属性。。。。。

@Expose

private String id;

@Expose

private String username;

//----------------------------

//不需要序列化的属性

private String createTime;

//set,get

//配置关系维护,双方不用放弃任何一方

//网上其他的好像写序列化过滤策略,或属性值过滤策略,看的不是很懂,就简单的先用现在的吧。。。

//----------------------------------

刚刚又犯了一个错误:

<jsp:include page="../include/top.jsp">

<c:paramname="tag"value="contact"/>

 </jsp:include>

----------------------

中间的写成c标签的了,正确的应该为:

<jsp:include page="../include/top.jsp">

<jsp:paramname="tag"value="contact"/>

 </jsp:include>

这样解析到json中的数据就不再有createTime属性

------------------------------------(异常)

org.apache.jasper.JasperException: /WEB-INF/content/message/list-success.jsp(17,7) Expecting "jsp:param" standard action with "name" and "value" attributes

--------------------------------------------------------------------------------

话说gson循环引用的解决方法,一种是只序列化需要的元素,

第二种就是配置生成策略,下面是从网上找的一篇例子:

//gsonbulider创建对象:
public class GsonFactory {

    public static Gson build(final List<String> fieldExclusions, final List<Class<?>> classExclusions) {
        GsonBuilder b = new GsonBuilder();
        b.addSerializationExclusionStrategy(new ExclusionStrategy() {     //过滤策略
            @Override
            public boolean shouldSkipField(FieldAttributes f) {    //需要过滤的字段
                return fieldExclusions == null ? false : fieldExclusions.contains(f.getName());
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {   //需要过滤的类
                return classExclusions == null ? false : classExclusions.contains(clazz);
            }
        });
        return b.create();

    }
}
 
//使用实例
static {
 List<String> fieldExclusions = new ArrayList<String>();
 fieldExclusions.add("id");
 fieldExclusions.add("provider");
 fieldExclusions.add("products");

 List<Class<?>> classExclusions = new ArrayList<Class<?>>();
 classExclusions.add(Product.class);
 GSON = GsonFactory.build(null, classExclusions);
}

private static final Gson GSON;

public String getSomeJson(){
    List<Provider> list = getEntitiesFromDatabase();     //从数据库生成list集合
    return GSON.toJson(list);
}

 下面是我自己的处理方法:举例(一个组对应多个用户)

package com.lk.pojo;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;

import com.google.gson.annotations.Expose;


@Entity
@Table(name="t_user")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {

	@Expose
	private String id;
	@Expose
	private String username;
	@Expose
	private String password;
	@Expose
	private String email;
	@Expose
	private String createTime;
	@Expose
	private boolean enable;
        private UserGroup userGroup;                              
//这个脑袋上什么都不加
	
	
	@Id
	@GenericGenerator(name="userid",strategy="uuid")
	@GeneratedValue(generator="userid")
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getCreateTime() {
		return createTime;
	}
	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}
	public boolean isEnable() {
		return enable;
	}
	public void setEnable(boolean enable) {
		this.enable = enable;
	}
	/**
	 * 用户分组(多个用户在一个组里)
	 * @return
	 */
	@ManyToOne
	@JoinColumn(name="groupid")
	public UserGroup getUserGroup() {
		return userGroup;
	}
	public void setUserGroup(UserGroup userGroup) {
		this.userGroup = userGroup;
	}
	
	
	
	
}
 
package com.lk.pojo;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;

import com.google.gson.annotations.Expose;

@Entity
@Table(name="t_usergroup")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class UserGroup {

	@Expose
	private String id;
	@Expose
	private String groupName;
	@Expose
	private String createTime;
        @Expose
        private List<User> userList;            //这个脑袋上加@Expose



	
	@Id
	@GenericGenerator(name="usergroupid",strategy="uuid")
	@GeneratedValue(generator="usergroupid")
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getGroupName() {
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}
	public String getCreateTime() {
		return createTime;
	}
	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}
	
	
	@OneToMany(mappedBy="userGroup")
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	
	
}

 json生成,我用的Gson,不过原理都是一样的吧........

@ParentPackage("json-default")
@Namespace("/user")
public class UserJsonAction extends BaseAction{

private static final long serialVersionUID = 1L;

@Action(value="userJson",
			results={@Result(name=SUCCESS,type="json")
	})
	public String userJson() throws IOException{
		userList = userService.findAll();
		userJson = getGson().toJson(userList);
		
		getResponse().setContentType("application/json,charset=UTF-8");
		PrintWriter out = getResponse().getWriter();
		out.print(userJson);
		out.flush();
		out.close();
		
		return SUCCESS;
	}
public Gson getGson(){
		GsonBuilder gb=new GsonBuilder() ;  
		gb.excludeFieldsWithoutExposeAnnotation();          //没有加@Expose的那部分不要生成json

		Gson gson = gb.create();
		return gson;
	}

}

相关推荐