개발을 하다보면 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를 선언해준 뒤 code와 msg에 값을 입력한다. (위 json 데이터는 api형태의 data다.)
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 데이터가 맞는지 확인하는 방법은


https://jsonlint.com/


해당 사이트에서 확인 가능하다.




Validate Json 버튼을 눌렀을 때 

Valid JSON

결과가 나오면 정상적인 JSON 데이터 값이다.



+ Recent posts