|
안드로이드 개발 ArrayList 배열 개체를 JSON 으로 변경하는 방법 |
|
환경: Android Studio |
요즘은 데이터를 JSON 오브젝트로 만들어 전송합니다. JSON 은 속성, 값의 쌍으로 이루어진 데이터 오브젝트로 서버와의 통신을 위해 가장 많이 사용하고 있는 표준입니다. 간결하고 직관적이며 작성하기가 편하기 때문입니다. 안드로이드에서는 별도의 라이브러리 추가없이 쉽게 사용할 수 있습니다. 오늘은 ArrayList 에 담긴 객체를 JSON 배열로 변환하거나 반대로 JSON 형태의 문자열을 다시 ArrayList 객체에 담는 방법에 대해 알아 보겠습니다.
|
◎ ArrayList 를 JSON 으로 변경하는 방법 |
▼ 먼저 JSON 배열로 변환하기 위한 List 객체를 만듭니다.
class User {
String id;
String name;
String pwd;
}
ArrayList<User> userList = new ArrayList<>();
User user1 = new User();
user1.id = "AAA";
user1.name = "김삿갓";
user1.pwd = "111";
User user2 = new User();
user2.id = "BBB";
user2.name = "구상진";
user2.pwd = "222";
User user3 = new User();
user3.id = "CCC";
user3.name = "바디리";
user3.pwd = "333";
userList.add(user1);
userList.add(user2);
userList.add(user3);
▼ JSON 으로 변환하기 위한 소스는 다음과 같습니다. ArrayList 에 데이터를 꺼내기 위해 For 문을 돌렸습니다. JSONObject 에 하나씩 담아서 JSONArray 의 put 함수를 이용해 추가합니다.
// JSON 으로 변환
try {
JSONArray jArray = new JSONArray();//배열
for (int i = 0; i < userList.size(); i++) {
JSONObject sObject = new JSONObject();//배열 내에 들어갈 json
sObject.put("id", userList.get(i).id);
sObject.put("name", userList.get(i).name);
sObject.put("pwd", userList.get(i).pwd);
jArray.put(sObject);
}
Log.d("JSON Test", jArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
▼ 전체 소스는 다음과 같습니다. 단위 테스트를 이용해서 구현했습니다.
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
@RunWith(AndroidJUnit4.class)
public class JSONTest{
class User {
String id;
String name;
String pwd;
}
@Test
public void parsing() throws Exception {
ArrayList<User> userList = new ArrayList<>();
User user1 = new User();
user1.id = "AAA";
user1.name = "김삿갓";
user1.pwd = "111";
User user2 = new User();
user2.id = "BBB";
user2.name = "구상진";
user2.pwd = "222";
User user3 = new User();
user3.id = "CCC";
user3.name = "바디리";
user3.pwd = "333";
userList.add(user1);
userList.add(user2);
userList.add(user3);
// JSON 으로 변환
try {
JSONArray jArray = new JSONArray();//배열이 필요할때
for (int i = 0; i < userList.size(); i++) {
JSONObject sObject = new JSONObject();//배열 내에 들어갈 json
sObject.put("id", userList.get(i).id);
sObject.put("name", userList.get(i).name);
sObject.put("pwd", userList.get(i).pwd);
jArray.put(sObject);
}
Log.d("JSON Test", jArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
▼ 콘솔에 출력한 결과입니다. JSON 형태로 변환된 것을 알 수 있습니다.
[
{"id":"AAA","name":"김삿갓","pwd":"111"},
{"id":"BBB","name":"구상진","pwd":"222"},
{"id":"CCC","name":"바디리","pwd":"333"}
]
|
◎ JSON 을 ArrayList 로 변경하는 방법 |
▼ 다음은 반대와 변환한 JSON 오브젝트를 다시 ArrayList 로 만들어 보겠습니다. 만약 JSON 이 배열이라면 JSONArray 클래스를 이용해야 합니다. “[“, “]” 로 양 끝을 감싸고 있으면 배열입니다. 배열이 아닌데 JSONArray 의 생성자 파라미터로 넘기면 에러가 나겠죠.
@Test
public void jsonToArraylist() throws Exception {
StringBuffer sb = new StringBuffer();
String str =
"[{'id':'AAA','name':'김삿갓','pwd':'111'}," +
"{'id':'BBB','name':'구상진','pwd':'222'}," +
"{'id':'CCC','name':'바디리','pwd':'333'}]";
try {
JSONArray jarray = new JSONArray(str);
ArrayList<User> userList = new ArrayList<>();
for(int i=0; i < jarray.length(); i++){
JSONObject jObject = jarray.getJSONObject(i);
String id = jObject.getString("id");
String name = jObject.getString("name");
String pwd = jObject.getString("pwd");
sb.append("id:" + id + ", name:" + name + ", pwd:" + pwd + "\n");
User user = new User();
user.id = id;
user.name = name;
user.pwd = pwd;
userList.add(user);
}
Log.d("JSON", sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
▼ 콘솔에 실행한 결과는 다음과 같습니다.
▼ 좀더 복잡한 JSON 형태의 값을 꺼내 보겠습니다. Array 와 Object 가 섞여 있는 형태라서 parsing 연습하는데 도움이 될 겁니다.
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
@Test
public void jsonParsing(){
String str =
"{'menu': {" +
"'id': 'file'," +
"'value': 'File'," +
"'popup': {" +
"'menuitem': [" +
"{'value': 'New', 'onclick': 'CreateNewDoc()'}," +
"{'value': 'Open', 'onclick': 'OpenDoc()'}," +
"{'value': 'Close', 'onclick': 'CloseDoc()'}" +
"]" +
"}" + "}}" ;
try {
JSONObject obj = new JSONObject(str);
JSONObject menuObj = obj.getJSONObject("menu");
JSONObject popupObj = menuObj.getJSONObject("popup");
JSONArray menuitemArray = popupObj.getJSONArray("menuitem");
for(int i=0; i < menuitemArray.length(); i++){
JSONObject jObject = menuitemArray.getJSONObject(i);
String value = jObject.getString("value");
String onclick = jObject.getString("onclick");
Log.d("JSON", "value : " + value + ", onclick : " + onclick);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
'안드로이드 개발' 카테고리의 다른 글
| 안드로이드 개발 ERROR x86 emulation currently requires hardware acceleration 에러 (0) | 2018.10.17 |
|---|---|
| 안드로이드 개발 위젯 클릭(이벤트 연결) 으로 앱 실행하는 방법 (0) | 2018.09.21 |
| 안드로이드 개발 Fragment 화면 구성하는 방법 - FragmentActivity 로 화면 구성 (0) | 2018.09.18 |
| 안드로이드 개발 Fragment 와 Activity 의 통신하는 방법 (1) | 2018.08.31 |
| 안드로이드 개발 간단하게 위젯 만드는 방법 (0) | 2018.08.15 |
| 안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법 (3) | 2018.08.07 |
| 안드로이드(Android) 개발 Timer 구현하는 방법 (0) | 2018.07.05 |
| 안드로이드 개발 인터넷 연결(WI-FI, 3G, 4G) 구분해서 연결 확인하는 방법 (0) | 2018.07.02 |
