2012-09-07 57 views
0

我想在android中將以下json字符串轉換爲JSONObject。但它會拋出JSONException。過去幾個小時我一直在挖掘我的想法。請幫忙。JSON和Android。不能轉換JSON字符串到JSONObject

JSON字符串:

parseExchangeRate({"query": 
      {"count":1,"created":"2012-09-07T18:49:32Z","lang":"en-US","results": 
         {"row":{"rate":"55.395","name":"USD to INR"}}}}); 

例外:

Value <jsonobject>parseExchangeRate(of type java.lang.String cannot be converted to JSONObject 

代碼:

String result = convertStreamToString(instream); 
Log.d(TAG, result); //this outputs the above stated string 
JSONObject json = new JSONObject(result); // this line thows exception 

在此先感謝。

+0

鬆散'parseExchangeRate()' – RvdK

回答

2

什麼是JSON字符串?你說,它是,

parseExchangeRate({"query": 
       {"count":1,"created":"2012-09-07T18:49:32Z","lang":"en-US","results": 
         {"row":{"rate":"55.395","name":"USD to INR"}}}}); 

但看起來像一行JavaScript代碼。 JSON!= javascript。它看起來像你的網絡服務回傳JSONP響應。這很好,但由於您不是JavaScript客戶端,因此您需要從該響應中解析出實際的JSON字符串。

String result = convertStreamToString(instream); 
Pattern p = Pattern.compile("^.*?\\((.*?)\\);$", Pattern.DOTALL); 
Matcher m = p.matcher(result); 
if (m.matches()) { 
    String json = m.group(1); 
    JSONObject jo = new JSONObject(json); 
    ... 
} else { 
    // whoops 
} 
+0

謝謝。現在很清楚我沒有json的知識 – harshit

相關問題