마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Retrofit2 에서 객체 배열에 접근을 어떻게 해야하는지 모르겠어요

0 추천

프로젝트 진행중입니다.

 

현재 객체를 리스트로 생성했을 때 그 객체 하나하나에 접근하는 방법이 잘못된건지, 앱이 비정상적으로 계속 종료돼 질문 올립니다.

 

{
    "foods": [
        {
            "serial": 2,
            "foodname": "곱창",
            "context": "튜브상태이며 탄력섬유가 많은 곳으로 질기기 
                           때문에 고아서 맛을 우려내서 먹거나 파나 깨가 
                           든 소스에 무쳐서 굽거나 볶으면 별미다..",
            "like": 0
        }
    ],
    "words": [
        {
            "word": "쫄깃하다"
        },
        {
            "word": "고소하다"
        }
    ]
}

 위는 Json 이고

 

List<foods>foodlist;
List<words>foodword;

public List<foods> getFoodlist() { return foodlist; }
public List<words> getFoodword() { return foodword; }

클래스로 변환한것과

 

public class foods {
    String serial;
    String foodname;
    String context;
    String like;

    public void setSerial(String serial) {
        this.serial = serial;
    }

    public void setLike(String like) {
        this.like = like;
    }

    public void setFoodname(String foodname) {
        this.foodname = foodname;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public String getSerial() {
        return serial;
    }

    public String getLike() {
        return like;
    }

    public String getContext() {
        return context;
    }

    public String getFoodname() {
        return foodname;
    }
}

public class words {
    String word;

    public String getWord() {
        return word;
    }
}

클래스로 변환한 것입니다.

 

 

아래는 Retrofit 객체 생성해서 처리하던 부분 메소드입니다... 어떻게 해야할 지 잘 모르겠어요 도움 부탁드립니다

public void setSerial(){
            Retrofit retrofit=new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();


            detRetroInter service=retrofit.create(detRetroInter.class);
            Call<foodRetrofit> call=service.getDetail("2");
            call.enqueue(new Callback<foodRetrofit>() {
                @Override
                public void onResponse(Call<foodRetrofit> call, Response<foodRetrofit> response) {


                   foodRetrofit repo=response.body();

//여기까진 이상 무

 

//다른 예제를 보고 따라했으나 아래 repo.getFoodlist() .. .. 이부분의 코드부터 오류

//                    food.setContext(repo.getFoodlist().get(0).getContext());
//                    food.setFoodname(repo.getFoodlist().get(0).getFoodname());
//                    food.setLike(repo.getFoodlist().get(0).getLike());

                   // for(int i=0;i<repo.getFoodword().size();i++){
                       // words word=new words();
                       // wd+="#"+(repo.getFoodword().get(i).getWord())+" ";
                   // }
//
 


                }

                @Override
                public void onFailure(Call<foodRetrofit> call, Throwable t) {

                }
            });

        }

 

 

별하 (120 포인트) 님이 2018년 9월 22일 질문

1개의 답변

0 추천

한 번의 호출에 서로 다른 class 두 종류를 받아오려 하고 있는데...

실제로 API가 저런식으로 구성되어 있나요? 

제 생각에는 두 가지의 호출 URI가 다르던지, food 안에 word를 포함하는 구조일 것 같은데요.

food : {
   f1 : "f1",
   f2 : "f2",
   f3 : "f3",
   words : [
      word : {
         w : "w1"
      },
      word : {
         w : "w2"
      }
   ]
}

이런 식으로 말이죠...

 

이 경우 당연히 클래스 구성도 food 안에 ArrayList<Word>를 포함하는 식으로 바뀌어야 합니다.

익명사용자 님이 2018년 9월 26일 답변
...