jsondata
json Array 내부에 있는 Json 데이터 추출하여 배열에 저장하기
이런 Json배열 하나에 여러개의 Json이 있다고 가정했을 때
Json 값마다 있는 idx,link,description 키값을 사용해 데이터를 저장해보았다.
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
|
String eventArray = null; //Json Array를 String으로 저장하기 위한 변수 선언
try {
eventArray = loadHtml(); //loadHtml()는 Json Array를 파싱해서 String으로 가져오는 함수라 가정
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("결과물 : " + eventArray);
try {
JSONArray array = new JSONArray(eventArray); //JSONArray형식으로 파싱하기 위해 새로 선언해주며 eventArray를 집어 넣어준다.
list_cnt = array.length(); //Json 배열 내 JSON 데이터 개수를 가져옴
//key의 value를 가져와 저장하기 위한 배열을 생성한다
getDescription = new String[list_cnt]; //decription 저장용
getLink = new String[list_cnt]; //link 저장용
getImageUrl = new String[list_cnt]; //imageUrl 저장용
for (int i = 0; i < list_cnt; i++) { //JSONArray 내 json 개수만큼 for문 동작
JSONObject jsonObject = array.getJSONObject(i); //i번째 Json데이터를 가져옴
getDescription[i] = jsonObject.getString("description"); //descripton 값을 배열에 저장
getLink[i] = jsonObject.getString("link"); //link 값을 배열에 저장
getImageUrl[i] = jsonObject.getString("imageUrl"); //imageurl 값을 배열에 저장
Log.i("JSON Object", jsonObject + "");
Log.i("JsonParsing", getDescription[i] + "," + getLink[i] + "," + getImageUrl[i]);
}
|
cs |
Log로 찍어보면
JsonObject의 로그
I/JSON Object: {"idx":15858,"imageUrl":"http:\/\/img.cgv.co.kr\/Event\/Event\/2017\/0330\/some_240x200_01.jpg","link":".\/detail-view.aspx?idx=15858&menu=2","description":"<어느날>1+1 예매 이벤트"}
파싱해낸 데이터 description, link, imageUrl 순으로 파싱이 된 걸 볼 수 있다.
I/JsonParsing: <어느날>1+1 예매 이벤트,./detail-view.aspx?idx=15858&menu=2,http://img.cgv.co.kr/Event/Event/2017/0330/some_240x200_01.jpg
배열에 잘 들어갔는지 description을 예로 확인을 해보면
for(int i=0;i<description.length;i++){
System.out.println("배열값 : "+description[i]);
}
I/System.out: 배열값 : <시간위의 집>스타★라이브톡
I/System.out: 배열값 : <보통사람>1+1 예매권 2차 이벤트
I/System.out: 배열값 : <로즈> 기대평 이벤트
I/System.out: 배열값 : <공각기동대:고스트 인 더 쉘>예매 경품 이벤트
description 값만 따로 배열에 잘 들어가있음을 확인할 수 있다.
이제 파싱해낸 값으로 다양한 곳에 쓸 수 있다.
'지식메모 > JAVA' 카테고리의 다른 글
자바 Swing에서 ArrayList를 JcomboBox에 집어넣기 (1) | 2019.04.28 |
---|---|
자바 스윙으로 파일 열기창 구현 (0) | 2017.06.14 |
자바 일정구간 문자열 추출하기 (0) | 2017.03.24 |
eclipse java.lang.SecurityException: class "org.hamcrest.Matchers"' 에러 해결하기 (0) | 2017.03.13 |
자바 이미지 파일 포함하여 프레임바 아이콘 변경 후 실행가능한 jar 파일로 생성하기 (0) | 2015.10.15 |