DTO , VO를 통해서 Json Array로 파싱해서 보낼때
Json Array = [Json{
"Key":"Value",
"Key":"Value",
"Key":"Value",
"Key":"Value"
}]
JSON이란 : 객체를 전송용 자료형(String)으로 키-밸류로 이루어진 데이터구조
써야할 이유 : 개별적인 문자열 형태를 한꺼번에 모아서 한번에 보낼 수 있어서 편하다.
JSON Object의 구조: JSON이 여러개 있는 것
JSON Array의 구조: Array구조안에 JSON Object가 들어있는것
Smaple JSON에서 우리가 원하는 영화 데이터 불러오려면 어떤 키 값들을 써야할까
"boxOfficeResult"의 밸류값 안의 4번째 키값 "weeklyBoxOfficeList"
GSON이란 : JSON을 해석하기 쉽게 만드는 라이브러리
public class MainActivity extends AppCompatActivity {
TextView tv_result;
RequestQueue queue;
StringRequest request;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
tv_result = findViewById(R.id.tv_result);
String url = "http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchWeeklyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20220526";
queue = Volley.newRequestQueue(getApplicationContext());
// JSON구조 가져오기
request =new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// String 형태의 JSON 구조
try {
// try/catch문으로 예외처리를 넣어준다.
// boxOfficeResult이라는 객체
JSONObject allData = new JSONObject(response);
JSONObject boxOfficeResult=allData.getJSONObject("boxOfficeResult");
JSONArray weeklyBoxOfficeList =boxOfficeResult.getJSONArray("weeklyBoxOfficeList");
for(int i = 0; i < weeklyBoxOfficeList.length();i++){
JSONObject object_i = weeklyBoxOfficeList.getJSONObject(i);
String title = object_i.getString("movieNm");
String date = object_i.getString("openDt");
int rank = object_i.getInt("rank");
String movie = rank + " : " + title + " : " + date ;
tv_result.setText(tv_result.getText() + movie+ " \n");
// 모든 영화 정보 누적해서 tv_result에 setText
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Nullable
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
};
queue.add(request);
}
}