상세 컨텐츠

본문 제목

Android - JSON 데이터 파싱하는 방법

Android

by yjh0922 2022. 7. 12. 10:13

본문

public void onResponse(JSONObject response) 
{

            // 3. 서버로부터 응답(Response)를 받아서, 텍스트뷰에 표시한다.

            // API를 호출한 결과가 여기서 실행된다.
            // 따라서 우리는 여기에다가, 가사를 화면에 보여주는 코드를 작성.
            // 즉, txtLyrics 에 가사를 보여준다.

            Log.i("MyLyrics", response.toString());


            try
                {
                #JsonObject 에서, 내가 가져올 데이터가 문자열이면, getString("키)
                #내가 가져올 데이터가 정수이면, getInt("키")
                #내가 가져올 데이터가 float이면, getFloat("키")
                #내가 가져올 데이터가 double이면, getDouble("키")
                #내가 가져올 데이터가 리스트이면, getJsonArray("키")
                #내가 가져올 데이터가 딕셔너리형태이면, getJsonObject("키")
                #로 데이터를 가져올수 있다.
                    String lyrics = response.getString("lyrics");
                    txtLyrics.setText(lyrics);
                }

                catch (JSONException e)
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"네트워크 에러입니다.",Toast.LENGTH_SHORT).show();
                    return;
                }
                
                txtLyrics.setText(response.toString());

             }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("MyLyrics", error.toString());
            }
        });

관련글 더보기