Recent Posts
Recent Comments
Link
«   2024/04   »
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 27
28 29 30
Archives
Today
Total
관리 메뉴

KKGRAM

JSONObject의 get 사용 시 NullException 처리하기 본문

개발

JSONObject의 get 사용 시 NullException 처리하기

kkgram 2016. 2. 2. 09:45


JSONObject의 get 사용 시 NullException 처리하기




json형태의 string데이터를 jsonobject로 바꾸었을 때 가끔 누락되는 정보들이 있다. 하지만 원래 틀이 있다보니 그 틀대로 getString 를 해 오는데, 이게 Exception이 발생하면서 정말 귀찮다. 아무것도 모를땐 일일히 try catch로 예외처리를 해줘야 하는 줄 알았고, null 인지 체크만 하면 될 줄알았다. 그래서 소스가 항상 지저분했다. 예를 들자면



try{
	//event
	if(mode.equals("event")){
		c.setSeq(j.getString("seq"));
		if(j.getString("id").equals(null))c.setDevice_ID(j.getString("id"));
		if(j.getString("source").equals(null))c.setEvent_Source(j.getString("source"));
		if(j.getString("target").equals(null))c.setEvent_Target(j.getString("target"));
		if(j.getString("type").equals(null))c.setEvent_Type(j.getString("type"));
		if(j.getString("seq").equals(null)) c.setEvent_Seq(j.getString("seq"));
		if(j.getString("result").equals(null)) c.setEvent_Result(j.getString("result"));
		if(j.getString("xml").equals(null)) c.setEvent_Xml(j.getString("xml"));
	}
}catch(Exception e){
	System.out.println("문제" + mode);
}



이런 식으로 해 온거다. 근데 이게 또 어떤 데이터는 되는데 저렇게 해도 nullException이 난다는 거다. 분명 어제까지만 해도 저렇게 해서 null을 피해갔는데...! 아침에 와서 프로그램 돌리고 멘붕. 난 아직 허접하니까 괜차나 이런거에 멘붕 와도 괜찮아... 그리고 이제 해결 방법을 찾았다. 고맙게도 jsonobject에서 알아서 지원 해 준다. ㅎ 난 똥멍청이라 몰랐던거... 역시 사람은 배우고 봐야한다.



try{
	//event
	if(mode.equals("event")){
		c.setSeq(j.getString("seq"));
		if(j.has("id"))c.setDevice_ID(j.getString("id"));
		if(j.has("source"))c.setEvent_Source(j.getString("source"));
		if(j.has("target"))c.setEvent_Target(j.getString("target"));
		if(j.has("type"))c.setEvent_Type(j.getString("type"));
		if(j.has("seq")) c.setEvent_Seq(j.getString("seq"));
		if(j.has("result")) c.setEvent_Result(j.getString("result"));
		if(j.has("xml")) c.setEvent_Xml(j.getString("xml"));
	}
}catch(Exception e){
	System.out.println("문제" + mode);
}



이렇게 해 주면 알아서 있는지 없는지 체크해서 넣어준다. 감사 베리베리땡큐. 이제 잊지말고 써먹겠다. 




Comments