JAVA - 2개 이상의 JSONObject 합치기(merge)

GARY·2022년 4월 12일
0

프로젝트 진행 중 API를 통해 JSONObject를 받고 추가로 내가 만든 JSONObject를 합쳐서 리턴해야 하는 경우가 발생했다.

@RequestMapping(value = "/jsonMerge")
public JSONObject jsonMerge(HttpServletRequest request, ModelMap model) throws Exception {
	
	//시즌별 티어 - jsonArray
	JSONArray jsonArrST = new JSONArray();
	String[] season = {"2018", "2019", "2020", "2021"};
	String[] tier = {"Bronze", "Silver", "Gold", "Platinum"};
	for(int i=0; i<4; i++){
		JSONObject jsonST = new JSONObject();
		jsonST.put("season", season[i]);
		jsonST.put("tier", tier[i]);

		jsonArrST.add(jsonST);
	}
	
	//merge할 jsonObject1
	JSONObject jsonPart1 = new JSONObject();
	jsonPart1.put("name", "GARY");
	jsonPart1.put("age", "25");
	jsonPart1.put("seasonTier", jsonArrST);
	jsonPart1.put("nickName", "초코잠보");

	//merge할 jsonObject2
	JSONObject jsonPart2 = new JSONObject();
	jsonPart2.put("status", 200);
	jsonPart2.put("message", "SUCCESS");

	//최종으로 보낼 jsonObject
	JSONObject jsonRes = new JSONObject();
	JSONObject[] objs = new JSONObject[] { jsonPart1, jsonPart2 };
	for (JSONObject obj : objs) {
		Iterator it = obj.keySet().iterator();
		while (it.hasNext()) {
			String key = (String)it.next();
			jsonRes.put(key, obj.get(key));
		}
	}

	return jsonRes;

}

실행시켜보면 jsonPart1과 jsonPart2가 잘 합쳐졌다!

profile
개발하는 개린이 개리

0개의 댓글