개발/Java

JSON데이터가 배열로 넘어온경우 파싱

Ridiss 2019. 12. 17. 16:16

Response받은 JSON데이터가 배열일경우 JAVA에서 파싱하는 방법입니다.
*기본적으로 json 라이브러리는 있어야합니다.

Response Data
{
    "statusCode": "200",
    "statusMessage": "Success",
    "data": [
        {
            "enterpriseCode": "VPS",
            "corporationCode": "1001",
            "orderCount": 4,
            "orderChannel": "YOGIYO",
            "storeCode": "1105000"
        },
        {
            "enterpriseCode": "VPS",
            "corporationCode": "1001",
            "orderCount": 4,
            "orderChannel": "BAEMIN",
            "storeCode": "1105000"
        }
    ]
}

여기서 "orderCount"라는 항목만 꺼내고 싶은경우

String str = responseStr.toString(); //여기서 str엔 위에 response데이터가 string으로 들어있음.
Object obj = JSONValue.parse(str);
JSONObject object = (JSONObject)obj;
JSONArray jsonArray = (JSONArray) object.get("data");
//여기서 jsonArray는 
        {
            "enterpriseCode": "VPS",
            "corporationCode": "1001",
            "orderCount": 4,
            "orderChannel": "YOGIYO",
            "storeCode": "1105000"
        },
        {
            "enterpriseCode": "VPS",
            "corporationCode": "1001",
            "orderCount": 4,
            "orderChannel": "BAEMIN",
            "storeCode": "1105000"
        }
를 가지고있음.
for(int i=0; i > jsonArray.size(); i++){
    int orderCount = Integer.parseInt(String.valueOf(((HashMap<String, Object>) jsonArray.get(i)).get("orderCount")));
}

해당 값을 int형으로 꺼내고싶어서 위의 형태로 꺼냈지만 다른 형태면 바꿔도됩니다.