Android - 读取JSON文件数据

来源:互联网 发布:管家婆软件要多少钱 编辑:程序博客网 时间:2024/06/08 18:15

Android读取JSON文件数据

JSON - JavaScript Object Notation
是一种存储和交换文本信息的语法。
JSON对象在花括号中书写。用逗号来分隔值。
JSON数组在方括号中表示。数组中的值也用逗号进行分隔。

使用Android API19

首先把testjson.json放在assets文件夹中

{    "role":[        {"id":1,"name":"Tom","say":"don't move"},        {"id":2,"name":"Jerry","say":"catch me if you can"}    ],    "dog":"Ben"}

创建一个TextView来显示读取到的数据。
先将JSON文件中的字符读出来,然后创建JSONObject。
实例化JSONObject后可以取出其中的对象。比如数组。
实例化JSONArray数组后,可以读出数组中的对象。而从数组中取得的对象,也是JSONObject类型的。读取对象的时候,需要注意返回类型。文件中的”name”是String型的。
最后用text.append(“”)的方式来组合出一个String,放到TextView中显示取得的数据。
以下是MainActivity.java

import java.io.BufferedReader;import java.io.InputStreamReader;import org.json.JSONArray;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;public class MainActivity extends Activity {    TextView text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        text = (TextView) findViewById(R.id.text1);        try {            InputStreamReader isr = new InputStreamReader(getAssets().open("testjson.json"),"UTF-8");            BufferedReader br = new BufferedReader(isr);            String line;            StringBuilder builder = new StringBuilder();            while((line = br.readLine()) != null){                builder.append(line);            }            br.close();            isr.close();            JSONObject testjson = new JSONObject(builder.toString());//builder读取了JSON中的数据。                                                                     //直接传入JSONObject来构造一个实例            JSONArray array = testjson.getJSONArray("role");         //从JSONObject中取出数组对象            for (int i = 0; i < array.length(); i++) {                JSONObject role = array.getJSONObject(i);    //取出数组中的对象                text.append(role.getString("name") + ": ");  //取出数组中对象的各个值                text.append(role.getString("say") + "\n");               }//            text.append("now the " +testjson.getString("dog") + " is here");        } catch (Exception e) {            e.printStackTrace();        }    }   }
0 0
原创粉丝点击