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);
}
}
'Android' 카테고리의 다른 글
| 이미지 처리를 위한 Glide 라이브러리 사용법 (0) | 2023.02.07 |
|---|---|
| 네트워크로부터 받은 Json 데이터에서, json 의 array 를 RecyclerView 로 처리 (0) | 2023.02.03 |
| 안드로이드 네트워크 통신을 위한 Volley 라이브러리 (0) | 2023.02.03 |
| 애뮬레이터에서 네트워크 통신 되도록 설정하는 방법 (0) | 2023.02.03 |
| TextWatcher 사용법 (1) | 2023.02.03 |