note

Read JSON 본문

Android/기본

Read JSON

투한 2012. 1. 13. 15:49

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,Asset InputStream 반환
        	AssetInputStream ais = (AssetInputStream)assetManager.open("sample.json");
        	//InputStream -> String 가공
        	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


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

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