簡體   English   中英

如何確定json對象是否為序列化字典?

[英]How to determine if json object is serialized dictionary?

我的應用程序對服務器進行了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以及如何循環?

注意
服務器發回的對象

您嘗試解釋該響應,然后查看它是否最終成為對象(或“字典”)。 如果響應看起來是JSON,並且其結果也是一個對象(“ Dictionary”),則您知道該字符串是一個對象(“ Dictionary”)。

下面的代碼應概述所有將其集成到自己的代碼中的必要技術。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM