顯示具有 json 標籤的文章。 顯示所有文章
顯示具有 json 標籤的文章。 顯示所有文章

2014年4月4日 星期五

Junit - 如何比較JsonArray是否相同?

參考:http://stackoverflow.com/questions/2253750/compare-two-json-objects-in-java

好久沒寫blog了,這陣子還是忙到昏天地暗,但也寫了一些HttpUnit的練習,有機會再來分享:)

json是很常使用的格式,我自己的專案也大量的運用它來傳遞訊息,那麼,如何比較兩個jsonArray是否相等呢?(或json)

用junit的assertEquals()是無法正確比較其中內容的,因此我們需要額外的方式:

  1. 下載JSONassert From Maven
  2. 使用:
    JSONAssert.assertEquals(expected,actual,false);
上述的第三個參數:boolean strict,說明,可參考doc上所寫:

There are two modes, strict and non-strict. In most cases, you will probably want to set strict to false, since that will make the tests less brittle.
Strict tests require all of the elements requested to be returned, and only those elements (ie, the tests are non-extensible). Arrays of elements must be returned in the same order as expected. For example, say I'm expecting:
{id:123,things['a','b','c']}The following would match when doing non-strict checking, but would fail on strict checking:
{id:123,things['c','b','a'],anotherfield:'blah'}

何時該使用strict(==true)就端看個人需求選擇囉~

2014年1月19日 星期日

從html上截取JSON出現轉換錯誤...


需求:從HTML上截取內容轉換為JSONObject
使用方式如下:

JSONObject json = new JSONObject(html);

卻出現exception:
 org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject


解決:
 我遇到的問題是,此截取的html為UTF-8編碼,因此開頭出現了UTF-8編碼字元如下圖:
而我存取的這個html存檔類型為UTF-8,最後我使用nopad++將檔案另外保存為『檔首無BOM』的形式就可以了.

使用nopad++『編輯』->『編譯成UTF-8碼(檔首無BOM)』