2011-09-05 46 views
0

我一直在使用JSONParser的解析方法沒有太多的問題。GWT JSONParser.parseStrict

最近,我決定要注意,我已經看到了取消通知。它建議我使用parseStrictparseLenient

所以,我決定嘗試parseStrict

我宣佈一個JSON字符串...

String jsonstr = "{value : [12,34],[56,78]]}"; 

...我證實,它具有良好的老parse工作...

JSONValue jsv = JSONParser.parse(jsonstr); 

...並警告窗口告訴我JSV的價值是這樣的:

{"value" : [12,34],[56,78]]} 

然後,我在同一個字符串中使用parseStrict

JSONValue jsv = JSONParser.parseStrict(jsonstr); 

但我的GWT應用程序崩潰,例外!

什麼是使用parseStrict(VS parse)的要求? Wny在這麼簡單的小json弦上做了旅行嗎?

Uncaught exception escaped 
com.google.gwt.event.shared.UmbrellaException: One or more exceptions caught, see full set in UmbrellaException#getCauses 
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:129) 
...... 
at com.google.gwt.json.client.JSONParser.evaluate(JSONParser.java) 
at com.google.gwt.json.client.JSONParser.parse(JSONParser.java:218) 
at com.google.gwt.json.client.JSONParser.parseStrict(JSONParser.java:87) 

回答

4

從最嚴格的意義上說,您提供的JSON並不嚴格正確。

JSON鍵值應該用雙引號as described in the JSON spec包圍,所以你的例子JSON應如下:

String jsonstr = "{\"value\" : [[12,34],[56,78]]}"; 

而且,看來你的括號([])不匹配(我有也糾正了)。

總之,它可以是缺少匹配的括號,或者缺少雙引號。爲了找到答案,你可以將有問題的代碼包裝在try/catch塊中,並按照堆棧跟蹤的建議進行操作。也就是說,調用異常的getCauses方法:

try { 
    JSONValue jsv = JSONParser.parseStrict(jsonstr); 
} catch (UmbrellaException e) { 
    Set causes = e.getCauses(); 
    //actually find out what the problem was 
} 

注:JSONParser.parse只是uses eval under the hood使用它的時候,所以要小心!

+0

方括號失配是錯字。在我的代碼中,沒有支架不匹配。在輸入這個問題時發生了錯字。 JSON中有很多括號! –