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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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);
	}

	public CacheObject(JSONArray jsonArray) {
		super();
		this.type = "JSONArray";
		this.value = JSON.toJSONString(jsonArray, SerializerFeature.WriteMapNullValue);
	}

	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 JSONArray toJSONArray() {
		try {
			if (value == null) {
				return null;
			}
			if ("JSONArray".equals(type)) {
				return JSON.parseArray(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;
		}
	}
}