我有以下文本文件到我的SdCard.Now我想通过Json解析器解析这个文件,我想解析并读取这个文件并将数据显示在我的文本视图中,我该怎么做?
{"data": [ { "ID": "1","Title": "Farhan Shah","duration": 10,},{ "ID": "2","Title": "Noman Shah",{ "ID": "3","Title": "Ahmad Shah",{ "ID": "4","Title": "Mohsin Shah",{ "ID": "5","Title": "Haris Shah",} ]}
这是代码:
file sdcard = Environment.getExternalStorageDirectory(); //Get the text file file file = new file(sdcard,"textarabics.txt"); String UTF8 = "utf8"; int BUFFER_SIZE = 8192; //Read text from file StringBuilder text = new StringBuilder();
我得到的文件,但现在我不知道我如何解析数据?
解决方法 使用 File从SD卡读取JsON文件,并使用 JSONObject进行解析.这里有一个起始码:
import org.Json.JsONArray;import org.Json.JsONException;import org.Json.JsONObject;public class ReadJsonfile {public Readfile (){ try { file yourfile = new file(Environment.getExternalStorageDirectory(),"path/to/the/file/insIDe_the_sdcard/textarabics.txt"); fileinputStream stream = new fileinputStream(yourfile); String JsonStr = null; try { fileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(fileChannel.MapMode.READ_ONLY,fc.size()); JsonStr = Charset.defaultCharset().decode(bb).toString(); } catch(Exception e){ e.printstacktrace(); } finally { stream.close(); }/* String JsonStr = "{\n\"data\": [\n {\n \"ID\": \"1\",\n \"Title\": \"Farhan Shah\",\n \"duration\": 10\n },\n {\n \"ID\": \"2\",\n \"Title\": \"Noman Shah\",\n {\n \"ID\": \"3\",\n \"Title\": \"Ahmad Shah\",\n {\n \"ID\": \"4\",\n \"Title\": \"Mohsin Shah\",\n {\n \"ID\": \"5\",\n \"Title\": \"Haris Shah\",\n \"duration\": 10\n }\n ]\n\n}\n"; */ JsONObject JsonObj = new JsONObject(JsonStr); // Getting data JsON Array nodes JsONArray data = JsonObj.getJsONArray("data"); // looPing through All nodes for (int i = 0; i < data.length(); i++) { JsONObject c = data.getJsONObject(i); String ID = c.getString("ID"); String Title = c.getString("Title"); String duration = c.getString("duration"); //use > int ID = c.getInt("duration"); if you want get an int // tmp hashmap for single node HashMap<String,String> parsedData = new HashMap<String,String>(); // adding each child node to HashMap key => value parsedData.put("ID",ID); parsedData.put("Title",Title); parsedData.put("duration",duration); // do what do you want on your interface } } catch (Exception e) { e.printstacktrace(); } }}
不要忘记在你的主播上添加读取存储:
<uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE" />总结
以上是内存溢出为你收集整理的Android如何从SD卡读取json文件(文本文件),并将数据显示到textview全部内容,希望文章能够帮你解决Android如何从SD卡读取json文件(文本文件),并将数据显示到textview所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)