如何判断json对象是否是序列化字典?

时间:2017-04-13 21:41:23

标签: javascript jquery

我的应用程序向服务器发出ajax POST,如果服务器验证失败,服务器会将stringDictionary<string, object>返回给客户端。

因此,如果服务器正在发送Dictionary,那么jQuery正在接收类似

的序列化responseText
"{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}"

我在客户端也有相应的responseJSON

    $.ajax({
        cache: false,
        type: 'POST',
        url: url,
        data: data            
    })            
    .fail(function (response, textStatus, errorThrown) {           
            if (response.status === '400') {
                if ($.isArray(response.responseJSON)) {
                    $.each(response.responseJSON, function (index, value) {
                        //do something
                    })
                }
                else if ($.type(response.responseJSON) === 'string') {
                      // do something
                }
            }               
        }

当响应是字典时,.isArray方法返回false。我如何确定responseJSON是Dictionary以及如何循环?

注意
服务器正在发回的object

1 个答案:

答案 0 :(得分:0)

您尝试解释响应并查看它是否最终成为对象(或&#34; Dictionary&#34;)。如果响应看起来是JSON,并且它的结果也是一个对象(&#34; Dictionary&#34;),那么你知道该字符串是一个对象(&#34; Dictionary&#34;)。

下面的代码应概述所有必要的技巧,以便将其集成到您自己的代码中。

var thatResponseJson = "{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}";
try {
    var result = JSON.parse(thatResponseJson);
    if (result instanceof Array) {
        // An Array
    } else if (typeof result === 'object' && thatResponseJson[0] === '{') {
        // Usually an object
    } else if (typeof result === 'string') {
        // A string
    } else {
        // Neither an Array, some other kind of object, or a string
    }
} catch (err) {
    // Not valid JSON
}
相关问题