2016-07-24 56 views
0

如果響應是JSON,我如何檢查Appcelerator?如何檢查服務器的響應是否是Appcelerator中的JSON對象?

我已經嘗試了通常的方式在js中。

Ti.API.info(response.constructor.name); // returns "String" 
if (response instanceof JSONObject) //JSON object undefined 

其他方式

 var response = this.responseText; 

     if (response.constructor === {}.constructor){ 
      Ti.API.info('is object'); 
      response = JSON.parse(response); 
     } 
     else{ 
      Ti.API.info('not object'); 
      Ti.API.info(response.constructor); // returns some Krollback <KrollCallback: 0x7fbdc8c0abe0> 
     } 

我使用子,但似乎只是存在缺陷。

if (response.substring(0, 1) === "{") 

回答

0

下面是我在做什麼,以驗證通過API發送的JSON響應:

// convert http response to json 
var CVT_ORDER_SEARCH_RESPONSE = JSON.parse(HttpResponse.responseText); 

// verify json response parse returned valid object 
if (!CVT_ORDER_SEARCH_RESPONSE){ 
    throw 'Invalid JSON response returned by server.'; 
} 

另見:JSON.parse Function (JavaScript)

+0

我知道這是一個JSON後,我通常解析響應,如果我試圖解析一個非JSON對象,我得到一個錯誤。 –

+2

@Von,我通常在try-catch-finally塊內處理這種情況,因爲我不確定當服務器向我發送不正確的JSON響應時,所以最好在try-catch而不是if-else中處理它們,因爲if-否則需要實際值和/或數據類型。 –

+0

去嘗試抓住。這是唯一的方法 –

1

繼PRASHANT和卡洛斯的建議下,我用一個try /抓住內部,謝謝你們。

 var response = this.responseText; 
     try { 
      console.log("success"); 
      var response = JSON.parse(response); 
      if (callback) 
       callback(response); 
     } 
     catch(e){ 
      console.log("error parsing"); 
      if (callback) 
       callback("error"); 
     } 
相關問題