assets 폴더에 sample.json 생성





{ 
     "menu":"회원관리", 
     "member":[ 
           { 
                 "id":"dragon", 
                 "name":"홍길동", 
                 "address":"서울시", 
                 "job":"학생" 
           }, 
           { 
                 "id":"sky", 
                 "name":"장영실", 
                 "address":"부산시", 
                 "job":"직장인"  
           } 
       ] 
} 


sample.json 파일정보





<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text"/>

</LinearLayout>


package kr.android.json;


import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class ReadJSONDemo extends Activity {


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		TextView text=(TextView)findViewById(R.id.text);

		//assets 폴더의 내용을 가져오기
		AssetManager assetManager= getResources().getAssets();

		try{
			//사용하고자 하는 json 파일 open , InputStream 반환
			AssetInputStream ais =(AssetInputStream)assetManager.open("sample.json");

			BufferedReader br= new BufferedReader(new InputStreamReader(ais,"utf-8"));

			StringBuffer sb=new StringBuffer();
			String result =null;

			while((result=br.readLine())!= null){
				sb.append(result);
			}
			//JSONObject 생성
			JSONObject jsonObject=new JSONObject(sb.toString());

			String menu = jsonObject.getString("menu");
			text.append(menu+"\n");

			//JSONArray
			JSONArray jArray = new JSONArray(jsonObject.getString("member"));

			for(int i=0;i<jArray.length();i++){
				text.append("============================\n");
				text.append(jArray.getJSONObject(i).getString("id")+"\n");
				text.append(jArray.getJSONObject(i).getString("name")+"\n");
				text.append(jArray.getJSONObject(i).getString("address")+"\n");
				text.append(jArray.getJSONObject(i).getString("job")+"\n");
			}
		}catch(JSONException e){
			Log.e("ReadJSONDemo",e.toString());
		}catch(Exception e){
			Log.e("ReadJSONDemo",e.toString());
		}
	}
}


ㅏㅏ


'Android > 기본' 카테고리의 다른 글

SD CARD (SD 카드에 저장하기)  (0) 2012.04.28
Access Web Image  (0) 2012.04.28
XML Resource  (0) 2012.04.28
StaticFile  (0) 2012.04.28
Read Write File (자동 저장할때 사용)  (0) 2012.04.28

+ Recent posts