개발을 하다보면 JSON으로 데이터, 또는 결과를 보여줘야 할 일이 있다.
자바에서 노가다로 짜는 법에 대해서 알려주고자 한다.
아래와 같은 json 데이터를 만들 예정이다.
{
"result": [{
"id": "1",
"entryName": "장원영",
"title": "이쁘다",
"thumbnail": "http://supercup.co.kr/entryImg/d11be93604df.gif",
"description": "이쁘게 움직이는 장원영 움짤",
"regDate": "2018-12-14 15:15:59",
"url": "http://supercup.co.kr/entry/detail?type=girlIdol&entryId=131"
}, {
"id": "2",
"entryName": "사나",
"title": "귀엽다",
"thumbnail": "http://supercup.co.kr/entryImg/bd7b77a5fc7c.jpg",
"description": "시상식 사나 클라스",
"regDate": "2018-11-19 13:30:44",
"url": "http://supercup.co.kr/entry/detail?type=girlIdol&entryId=56"
}],
"code": "100",
"msg": "success"
}
일단 import는 org.json.simple 버전으로 했다
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
JSONObject resultObj = new JSONObject();
resultObj.put("code","100");
resultObj.put("msg","success");
각 구성값을 넣어줄 JSONArray를 선언
JSONArray componentArray = new JSONArray();
JSONObject wyObj = new JSONObject(); //원영이 오브젝트
JSONObject snObj = new JSONObject(); //사나 오브젝트
wyObj.put("id","1");
wyObj.put("entryName","장원영");
wyObj.put("title","이쁘다");
wyObj.put("thumbnail","http://supercup.co.kr/entryImg/d11be93604df.gif");
wyObj.put("description","이쁘게 움직이는 장원영 움짤");
wyObj.put("regDate","2018-12-14 15:15:59");
wyObj.put("url","http://supercup.co.kr/entry/detail?type=girlIdol&entryId=131");
snObj.put("id","2");
snObj.put("entryName","사나");
snObj.put("title","귀엽다");
snObj.put("thumbnail","http://supercup.co.kr/entryImg/bd7b77a5fc7c.jpg");
snObj.put("description","시상식 사나 클라스");
snObj.put("regDate","2018-11-19 13:30:44");
snObj.put("url","http://supercup.co.kr/entry/detail?type=girlIdol&entryId=56");
//원영이, 사나 오브젝트 값 JSONArray에 입력
componentArray.add(wyObj);
componentArray.add(snObj);
resultObj.put("result",componentArray.toString());
String result = resultObj.toString().replaceAll("\"\\[" ,"\\[").replaceAll("\\]\"" ,"\\]").replaceAll("\\\\" ,"");
result에 해당값이 있다.
해당값이 정상적인 JSON 데이터가 맞는지 확인하는 방법은
해당 사이트에서 확인 가능하다.
Validate Json 버튼을 눌렀을 때
Valid JSON
결과가 나오면 정상적인 JSON 데이터 값이다.
'개발' 카테고리의 다른 글
[JAVA] FTP로 파일 업로드 / SFTP로 파일 업로드 (2) | 2019.04.08 |
---|---|
[JQUERY] masonry + lazy load (0) | 2019.03.13 |
[JQuery] 이중모달 사용 (0) | 2019.01.23 |
[java] 확률 소수점 자리까지 표시 (0) | 2019.01.09 |
javascript 문자열 특정문자 찾아서 자르기 (0) | 2019.01.09 |