安卓解析JSON文件

安卓解析JSON文件

根据JOSN文件的格式,文件只有两种数据,一是对象数据,以 {}为分隔,二是数组,以[]分隔

以下介绍安卓如何解析一个JSON文件,该文件存放在assets目录下,即:assets/xx.json

工程目录结构以及简单布局:

要解析的JSON文件数据

代码实现:

package com.lhy.nojsonfile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
    Button bt_Json;
    TextView tv_Json;
    @Override
    protected void onCreate ( Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt_Json = (Button) this.findViewById(R.id.bt_Json);
        bt_Json.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick ( View v)
            {
                bt_Json_click();
            }
        });
    tv_Json = (TextView) this.findViewById(R.id.tv_Json);
    }
    // 解析JSON文件
    protected void bt_Json_click ()
    {
        try
        {
        // 获取json文件数据源,流的方式呈现
        InputStream inputStream = this.getAssets().open("xx.json");
        // 读取JSON文件流
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String temp = "";
        String jsonSource = "";
            //一行一行的读取
            while ((temp = bufferedReader.readLine()) != null)
            {
                jsonSource += temp;
            }
        //关闭
        bufferedReader.close();
        inputStream.close();
        // JSON解析对象
        JSONObject jsonObject = new JSONObject(jsonSource);
        // 获取JOSN文件当中的数据对象weatherinfo【可知JSON文件数据只有两种,一是对象{},二是数组[]】
        JSONObject jsonObjectWeatherinfo = jsonObject.getJSONObject("weatherinfo");
        // JSOn文件某一数据对象的属性,例如weatherinfo对象的属性city
        String result = jsonObjectWeatherinfo.getString("city");
        tv_Json.setText(result);
        }
    catch (JSONException e)
    {
        e.printStackTrace();
        Log.i("lhy", "JSONException:" + e.toString());
    }
    catch (IOException e)
    {
        Log.i("lhy", "IOException:" + e.toString());
        e.printStackTrace();
    }
   }
}

结果:

 

posted on 2013-10-26 15:53  知行立远  阅读(1264)  评论(0编辑  收藏  举报