CacheObject.java 1.55 KB
package com.yoho.search.cache.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.Serializable;

/**
 * 暂时只支持JSONObject和jsonArray
 *
 * @author hugufei
 *
 */
public class CacheObject implements Serializable {

	private static final long serialVersionUID = -3949382156604252137L;

	private String type;
	private Object value;

	public CacheObject() {
	}

	public CacheObject(Object object) {
		super();
		this.type = "Object";
		this.value = object;
	}

	public CacheObject(JSONObject jsonObject) {
		super();
		this.type = "JSONObject";
		this.value = JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue,SerializerFeature.DisableCircularReferenceDetect);
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	public JSONObject toJSONObject() {
		try {
			if (value == null) {
				return null;
			}
			if ("JSONObject".equals(type)) {
				return JSON.parseObject(value.toString());
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object toObject() {
		try {
			if (value == null) {
				return null;
			}
			if ("Object".equals(type)) {
				return value;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}