안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Open API

Android Studio(기능) JSON [직접 .json파일 만들고 파싱 ]

차누감 2019. 10. 22. 12:42

CSV -> XML -> JSON

 

ex)

CSV  : SAM,Hello,   .csv확장자

 

XML : <name>SAM</name>

        <msg>Hello</msg>

 

JSON : {"name":"SAM","msg":"Hello"}

(JSON은 XML에 스타트 태그만 썼다..라고 알기, XML은 스타트, 앤드 태그가 많아서 무겁다.. 그래서 JSON이 나옴)

 

간단하게 JSON 파싱하는 예제를 하겠다.

 

우선 JSON파일을 담을 폴더를 만들자.

app에서 마우스 오른쪽 클릭->New->Folder->assets Folder

이제 파싱할 목록(JSON)을 만들겠다.

보통은 json파일을 구분하기 위해 assets폴더에 하위 폴더를 만들어서 구별한다.

하위 폴더를 만들고 json파일을 드래그 & 드롭을 하자.

그러면 아래 사진과 같이 하위 폴더에 json 파일이 들어간 것을 확인 할 수 있다.

이제 MainActivity.java 코드를 작성하자. (잘 읽어왔는지 확인 하는 코드)

json내용을 그대로 가져온 것을 알 수 있다.

이제 json 파싱이 잘되는 것을 알았으니, 화면에 보기 좋게 데이터를 가져오자.

 MainActivity.java 코드를 수정하자. 

보통 JSON 파싱하는 파일들은 여러 배열구조로 되어있다. 이때는 약간의 코드 수정이 필요하다.

 

 

<복붙용 최종 코드들>

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="json parse"
        android:onClick="clickBtn"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"/>
    
</LinearLayout>
 
 

MainActivity.java 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
 
 
 
 
 
public class MainActivity extends AppCompatActivity {
 
    TextView tv;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tv=findViewById(R.id.tv);
    }
 
    public void clickBtn(View view) {
 
        //json 파일 읽어와서 분석하기
 
        //assets폴더의 파일을 가져오기 위해
        //창고관리자(AssetManager) 얻어오기
        AssetManager assetManager= getAssets();
 
        try {
            InputStream is= assetManager.open("jsons/test.json");
            InputStreamReader isr= new InputStreamReader(is);
            BufferedReader reader= new BufferedReader(isr);
 
            StringBuffer buffer= new StringBuffer();
            String line= reader.readLine();
            while (line!=null){
                buffer.append(line+"\n");
                line=reader.readLine();
            }
 
            String jsonData= buffer.toString();
 
            //읽어온 json문자열 확인
            //tv.setText(jsonData);
 
            //json 분석
            //json 객체 생성
//            JSONObject jsonObject= new JSONObject(jsonData);
//            String name= jsonObject.getString("name");
//            String msg= jsonObject.getString("msg");
//
//            tv.setText("이름 : "+name+"\n"+"메세지 : "+msg);
 
            //json 데이터가 []로 시작하는 배열일때..
            JSONArray jsonArray= new JSONArray(jsonData);
 
            String s="";
 
            for(int i=0; i<jsonArray.length();i++){
                JSONObject jo=jsonArray.getJSONObject(i);
 
                String name= jo.getString("name");
                String msg= jo.getString("msg");
                JSONObject flag=jo.getJSONObject("flag");
                int aa= flag.getInt("aa");
                int bb= flag.getInt("bb");
 
                s += name+" : "+msg+"==>"+aa+","+bb+"\n";
            }
            tv.setText(s);
 
        } catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace(); }
 
    }
}
 
 
 

test.json 코드

1
2
3
4
[
{"name":  "sam","msg":  "Hello world", "flag": {"aa":  10, "bb":  20}},
{"name":  "robin","msg":  "Nice to meet you", "flag": {"aa": 100,"bb": 200}}
]