Parse JSON to POJO using Java

JSON response:

{"restRequest":{"id":1619,"sessionId":"b6f67825-1ed5-43e1-ba5f-1324550f5798",
"loanId":1123456,"creationDate":1392420577000,"knowledgeBaseName":"automation.drl"},
"finalOutcomeStatus":"REVIEW"}

Parsing the JSON to POJO:

private List<RESTResponseModel> restResponseArray = new ArrayList<RESTResponseModel>();
JSONArray jsonResponse = new JSONArray(getJsonResponse());
for (int k = 0; k<jsonResponse.length();k++){
        
    RESTResponseModel dm = new RESTResponseModel();
 	JSONObject restRequest=jsonResponse.getJSONObject(k);

	JSONObject restBody = restRequest.optJSONObject("restRequest");
				
	dm.setId(restBody.optString("id"));
	dm.setSessionId(restBody.optString("sessionId"));
					
	if (new Long(restBody.optLong("creationDate"))!=null){
		Date date = new Date(restBody.optLong("creationDate"));
		dm.setCreationDate(new SimpleDateFormat("MM/dd/yyyy").format(date));
    }
					
	dm.setKnowledgeBaseName(restBody.optString("knowledgeBaseName"));
	dm.setFinalOutcomeStatus(restRequest.optString("finalOutcomeStatus"));
	restResponseArray.add(dm);
}

RESTResponseModel POJO


public class RESTResponseModel {
	
	private String id;
	private String sessionId;
	private String creationDate;
	private String knowledgeBaseName;
	private String finalOutcomeStatus;	
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getSessionId() {
		return sessionId;
	}
	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}
	public String getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(String creationDate) {
		this.creationDate = creationDate;
	}
	public String getKnowledgeBaseName() {
		return knowledgeBaseName;
	}
	public void setKnowledgeBaseName(String knowledgeBaseName) {
		this.knowledgeBaseName = knowledgeBaseName;
	}
	public String getFinalOutcomeStatus() {
		return finalOutcomeStatus;
	}
	public void setFinalOutcomeStatus(String finalOutcomeStatus) {
		this.finalOutcomeStatus = finalOutcomeStatus;
	}
}
Advertisements

2 Comments on “Parse JSON to POJO using Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: