Android: JSON資料解析--JSONlib與org.JSON的衝突

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   color   os   使用   

新註冊了這個blog,正好這兩天學寫Android,需要解析本地的JSON檔案,google一搜看到JSONlib這玩意兒挺靠譜,就大刀闊斧下了相關依賴包幹了起來,沒想到這下掉進了一個深坑,網上也查不到原因,在血海裡翻騰了兩天,如今好不容易爬了出來,與君分享,也作為開篇之作,不足之處還望指正。

 

對於初次解析JSON檔案的童鞋可能會上網尋找解析JSON檔案的方法,於是網上有諸如JSONLIB, FASTJSON, GSON等方式,於是看的眼花撩亂。

 

其實。。我想說,Android內建的org.json包完全可以完成這個任務。。沒必要去下載那些外部包

 

更坑的是,JSONLIB和Android內建的org.json包是衝突的。。which means, 你如果在java的開發環境下使用JSONLIB,完全沒問題,不過你如果用Android的開發環境,不好意思,會報錯

 

Error Message: AndroidRuntime java.lang.NoClassDefFoundError: Failed resolution of :Lnet/......JSONArray

這個原因完全是因為JSONLIB和org.JSON在包的命名上存在衝突 (當時我查的昏天黑地,反覆糾結,在Java項目下用的好好地JSONLIB,為什麼一放到Android就不行了呢,真是個大坑)

 

其實,JSONLIB與org.JSON的文法類似,

除了在建立對象時有所不同

JSONArray ja = new JSONArray(res);       org.JSON

 

JSONArray ja = new JSONArray();            JSONLIB

ja.from(res)               

在實際使用時兩者幾乎沒有區別 e.g.

ja.getJb().getJSONArray("comments").getJSONObject(j).getString("time_created").toString()

 

 1 import java.io.InputStream; 2  3 import org.apache.http.util.EncodingUtils; 4 import org.json.JSONArray; 5 import android.content.Context; 6 import com.example.test.R; 7  8 public class InitJson{ 9     public  String sJsonResource;10     public  JSONArray ja;11     public  void init(Context context) {12         try {13             //讀取JSON檔案14             InputStream in = context.getResources().openRawResource(15                     R.raw.community);16             int length = in.available();17             byte[] buffer = new byte[length];18             in.read(buffer);19             sJsonResource = EncodingUtils.getString(buffer, "BIG5");20             in.close();21             ja = new JSONArray(sJsonResource);22             in.close();23             for (int i = 0; i < ja.length(); ++i) {24                 ja.getJSONObject(i).getString("time_created").toString();25             }26         } catch (Exception e) {27             e.printStackTrace();28         }29 30     }31 }

 

 

Last but no least

 

壓根沒必要去用外部庫,Android內建的org.json就能解決你的一切關於JSON檔案解析的問題,而且,並不複雜!

Android: JSON資料解析--JSONlib與org.JSON的衝突

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.