/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.lang;

import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;


public class JsonUtils {
	@SuppressWarnings("unchecked")
	public static <T> T fromJson(String json, Class<T> clazz) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.NOPROP);
		
		if (clazz.isArray()
				|| List.class.isAssignableFrom(clazz)
				|| Set.class.isAssignableFrom(clazz)) {
			JSONArray ja = JSONArray.fromObject(json, jsonConfig);
			jsonConfig.setRootClass(clazz);
			return (T)JSONArray.toCollection(ja, jsonConfig);
		}
		else {
			JSONObject jo = JSONObject.fromObject(json, jsonConfig);
			jsonConfig.setRootClass(clazz);
			return (T)JSONObject.toBean(jo, jsonConfig);
		}
	}

	public static String toJson(Object value) {
		return toJson(0);
	}

	public static String toJson(Object value, int indent) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		Class clazz = value.getClass();
		if (clazz.isArray()
				|| List.class.isAssignableFrom(clazz)
				|| Set.class.isAssignableFrom(clazz)) {
			JSONArray ja = JSONArray.fromObject(value, jsonConfig);
			return ja.toString(indent);
		}
		else {
			JSONObject jo = JSONObject.fromObject(value, jsonConfig);
			return jo.toString(indent);
		}
	}
}
