Light Blue Pointer
본문 바로가기
Developing/개발일지

2023-12-05, Today I Learned

by Greedy 2023. 12. 5.

 

JSONArray items  = jsonObject.getJSONArray("items");

List<ItemDto> itemDtoList = new ArrayList<>();

for (Object item : items) {
    ItemDto itemDto = new ItemDto((JSONObject) item);
    itemDtoList.add(itemDto);
}

이 코드를 보고 JSONObject를 꺼내는데 그냥 JSONObject로 받으면 되지 않나 왜 Object로 받아서 (JSONObject)로 type casting을 다시 하는지 의문이었는데

for each에서는 typecasitng을 못 쓴다고 함

JSONArray arr = ...; // <-- got by some procedure
for(JSONObject o: arr){
    parse(o);
}

When I try to compile this code, indeed I get "incompatible types" error, even though it looks so natural. So, my question is what is the best way to iterate through JSONArray?

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

 

java 8 이상에서는 다음과 같은 방법으로 하면 된다고 한다!

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

 

⚠️ String replace를 하면 다시 넣어줘야 값이 변한다

str.replace("$","");

이렇게 하는데 아무리 해도 $가 안 사라지는 거임

그래서 아 대체 왜 저러는거야 이랬는데

str = str.replace("$","");

이렇게 넣어줘야 한다는 걸 발견했다

 

 

'Developing > 개발일지' 카테고리의 다른 글

2023-12-07, Today I Leanred  (1) 2023.12.07
2023-12-06, Today I Leanred  (2) 2023.12.06
2023-12-04, Today I Learned  (0) 2023.12.04
2023-11-30, Today I Learned  (0) 2023.11.30
2023-11-29, Today I Learned  (0) 2023.11.29