var verify = require('./verify');

//实体对象转JSON
var objToJson = function (model) {
    try {
        return JSON.parse(JSON.stringify(model));
    }
    catch (ex) {
        return undefined;
    }
}
exports.objToJson = objToJson;

//JSON字符串转实体对象
var jsonStrToJson = function (jsonStr) {
    var result = undefined;
    try {
        result = JSON.parse(jsonStr)
    }
    catch (ex) {
    }
    return result;
}
exports.jsonStrToJson = jsonStrToJson;

//object转string
var objToStr = function (obj) {
    if (obj && typeof obj == 'string') {
        return obj;
    }
    if (obj) {
        if (verify.isJson(obj) || verify.isJsonArray(obj)) {
            return JSON.stringify(obj);
        }
        else if (verify.isArray(obj)) {
            var tmp = "[";
            for (var i in obj) {
                if (typeof obj[i] == 'object') {
                    tmp += objToStr(obj[i]);
                }
                else {
                    tmp += obj[i] + ",";
                }
            }
            tmp = tmp.EndWith(tmp, ",") ? tmp.substring(0, tmp.length - 1) : tmp;
            return tmp + "]";
        }
        else if (verify.isObject(obj)) {
            var tmp = "";
            for (var i in obj) {
                if (typeof obj[i] == 'object') {
                    tmp += objToStr(obj[i]);
                }
                else {
                    tmp += obj[i] + ",";
                }
            }
            return tmp.EndWith(tmp, ",") ? tmp.substring(0, tmp.length - 1) : tmp;
        }
        else {
            return obj.toString();
        }
    }
    return "";
}
exports.objToStr = objToStr;