Java Json parsing

정재현·2022년 11월 15일
0

Json parsing

dependency에 추가

implementation 'org.json:json:20190722'

1. 데이터 형식 확인

        String jsonData = "{\n" +
                "   \"items\": [\n" +
                "     {\n" +
                "       \"label\": \"블루 진\",\n" +
                "       \"price\": 80000\n" +
                "     },\n" +
                "     {\n" +
                "       \"label\": \"후드 티\",\n" +
                "       \"price\": 30000\n" +
                "     },\n" +
                "     {\n" +
                "       \"label\": \"무지 반팔\",\n" +
                "       \"price\": 200000\n" +
                "     }\n" +
                "   ]\n" +
                "}";

배열 형식으로 제공 될 때

2. String to Json

  • String to Json
JSONObject jsonObject = new JSONObject(jsonData);
  • Key(item)를 기준으로 JSONArray에 추가
JSONArray jsonArray = jsonObject.getJSONArray("items");
List<JSONObject> items = new ArrayList<>();

        for(int i=0; i<jsonArray.length(); i++){
            items.add(jsonArray.getJSONObject(i));
		}

정렬

Collections.sort(items, new Comparator<JSONObject>(){
            @Override
            public int compare(JSONObject a, JSONObject b){
                int aPrice = a.getInt("price");
                int bPrice = b.getInt("price");

                return bPrice - aPrice;
            }
        });
{"price":80000,"label":"블루 진"}
{"price":30000,"label":"후드 티"}
{"price":20000,"label":"무지 반팔"}
profile
back end개발자로 성장하기

0개의 댓글

관련 채용 정보