Android

JSON 데이터 파싱하는 방법

yugyeong 2023. 2. 3. 16:46

 

JSON 데이터를 파싱하기 위해서는 먼저 JsonObjectRequest 로 request 를 생성해준다.

 

파라미터값에는

  • 데이터를 가져오는 것이기 때문에 GET,
  • json URL,
  • null,
  • new Response.Listener -> 데이터를 잘 가져왔을 때 처리할 코드 작성,
  • new Response.ErrorListener -> 데이터 가져올 때 에러 발생할 경우 처리할 코드 작성

 

Parsing 파싱

데이터를 파싱할 때는 int 형은 response.getInt(json 의 key 값);

String 형은 getString 을 사용하여서 파싱한다.

 

JsonObjectRequest request = new JsonObjectRequest(
        Request.Method.GET,
        URL + "/posts/1",
        null,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

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

                // response 에 데이터가 있으니
                // 이 데이터를 Parsing 한다.
                try {
                    int userId = response.getInt("userId");
                    int id = response.getInt("id");
                    String title = response.getString("title");
                    String body = response.getString("body");

                    // 화면에 셋팅
                    txtUserId.setText(userId+"");
                    txtId.setText(id+"");
                    txtTitle.setText(title);
                    txtBody.setText(body);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "파싱 에러", Toast.LENGTH_SHORT).show();
                    return;

                }

            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }
);
// 이 코드가 있어야, 네트워크 실행한다.

queue.add(request);

 

 

전체 코드

xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="415dp"
        android:layout_height="636dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/txtUserId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="TextView"
            android:textSize="28sp" />

        <TextView
            android:id="@+id/txtId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="TextView"
            android:textSize="28sp" />

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="TextView"
            android:textSize="28sp" />

        <TextView
            android:id="@+id/txtBody"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="TextView"
            android:textSize="28sp" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 

java

public class MainActivity extends AppCompatActivity {

    TextView txtUserId;
    TextView txtId;
    TextView txtTitle;
    TextView txtBody;

    final String URL = "https://jsonplaceholder.typicode.com";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtUserId = findViewById(R.id.txtUserId);
        txtId = findViewById(R.id.txtId);
        txtTitle = findViewById(R.id.txtTitle);
        txtBody = findViewById(R.id.txtBody);

        // Volley 로 네트워크 통신한다.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

        JsonArrayRequest request = new JsonArrayRequest(
                Request.Method.GET,
                URL + "/posts",
                null,
                // 정상적으로 왔을 때 처리 방법

                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.i("NETWORK_APP", response.toString());

                        try {
                            int userId = response.getJSONObject(0).getInt("userId");
                            int id = response.getJSONObject(0).getInt("id");
                            String title = response.getJSONObject(0).getString("title");
                            String body = response.getJSONObject(0).getString("body");

                            // 화면에 셋팅
                            txtUserId.setText(userId+"");
                            txtId.setText(id+"");
                            txtTitle.setText(title);
                            txtBody.setText(body);


                        } catch (JSONException e) {
                            Toast.makeText(MainActivity.this, "파싱 에러", Toast.LENGTH_SHORT).show();
                            return;

                        }

//                        // 첫번째 데이터를 화면에 표시하시오.


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );

//        JsonObjectRequest request = new JsonObjectRequest(
//                Request.Method.GET,
//                URL + "/posts/1",
//                null,
//                new Response.Listener<JSONObject>() {
//                    @Override
//                    public void onResponse(JSONObject response) {
//
//                        Log.i("NETWORK_APP", response.toString());
//
//                        // response 에 데이터가 있으니
//                        // 이 데이터를 Parsing 한다.
//                        try {
//                            int userId = response.getInt("userId");
//                            int id = response.getInt("id");
//                            String title = response.getString("title");
//                            String body = response.getString("body");
//
//                            // 화면에 셋팅
//                            txtUserId.setText(userId+"");
//                            txtId.setText(id+"");
//                            txtTitle.setText(title);
//                            txtBody.setText(body);
//
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                            Toast.makeText(MainActivity.this, "파싱 에러", Toast.LENGTH_SHORT).show();
//                            return;
//
//                        }
//
//                    }
//                },
//                new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError error) {
//
//                    }
//                }
//        );

        // 이 코드가 있어야, 네트워크 실행한다.

        queue.add(request);

    }
}