개발학습일지

[Android Studio] JSON 데이터 파싱 방법 본문

Android Studio

[Android Studio] JSON 데이터 파싱 방법

처카푸 2024. 6. 11. 14:16

JSON 데이터 파싱 방법

 

1. JSON 데이터를 반복문으로 꺼내기

for(int i = 0 ; i < dataArray.length() ; i++) {
    JSONObject data = dataArray.getJSONObject(i);
    int id = data.getInt("id");
    int userId = data.getInt("userId");
    String title = data.getString("title");
    String body = data.getString("body");

}

 

2. 데이터를 받아줄 model  자바클래스 파일 만들기

- 생성자 만들어서 데이터 객체로 저장

public class Posting {

    public int id;
    public int userId;
    public String title;
    public String body;

    public Posting() {}

    public Posting(int id, int userId, String title, String body) {
        this.id = id;
        this.userId = userId;
        this.title = title;
        this.body = body;
    }
}

 

⬇︎

- 반복문에 추가로 입력한다.

for(int i = 0 ; i < dataArray.length() ; i++) {
    JSONObject data = dataArray.getJSONObject(i);
    int id = data.getInt("id");
    int userId = data.getInt("userId");
    String title = data.getString("title");
    String body = data.getString("body");
    
    // 생성자로 만든 posting 객체 만들기
    Posting posting = new Posting(id, userId, title, body);

}

 

3. 어뎁터 자바클래스 만들기

- 객체들을 연결에서 저장할 ArrayList 만들기

- 순서에 맞게 코드 작성

// 2. 뷰홀더랑 연결
public class PostingAdapter extends RecyclerView.Adapter<PostingAdapter.ViewHolder> {
	
    // 3. MainActivity
    Context context;
    ArrayList<Posting> postingArrayList;
	
    // 4. 생성자
    public PostingAdapter(Context context, ArrayList<Posting> postingArrayList) {
        this.context = context;
        this.postingArrayList = postingArrayList;
    }
	
    // 5.
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 복붙 _ 화면 연결 부분
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.posting_row, parent, false);
        return new PostingAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // holer 화면, position 인덱스
        Posting posting = postingArrayList.get(position);

        holder.txtTitle.setText(posting.getTitle());
        holder.txtBody.setText(posting.getBody());
    }

    @Override
    public int getItemCount() {
        return postingArrayList.size();
    }
	
    // 1.
    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView txtTitle;
        TextView txtBody;
        ImageView imgDelete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txtTitle = itemView.findViewById(R.id.txtTitle);
            txtBody = itemView.findViewById(R.id.txtBody);
            imgDelete = itemView.findViewById(R.id.imgDelete);

        }
    }

}

 

 

4. 어뎁터와 연결할 화면 개발 res/layout/~~.xml

- 화면에 보여주고 싶은 데이터 ID 값 잘 지정해서 adapter 자바클래스랑 잘 연결한다.

 

5. JSON 데이터 파싱 완료 

- 멤버변수 생성

    // 리사이클러뷰는 한번에 설정하자
    RecyclerView recyclerView;
    ArrayList<Posting> postingArrayList = new ArrayList<>();
    PostingAdapter adapter;

- 화면 이어 주기(세트!! 무조건 3줄 모두 작성)

        // 리사이클러뷰는 한번에 설정
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

- try{} catch{} 로 반복문 완성 ( try{} catch{}  필수!!)

                        try {
                            progressBar.setVisibility(View.GONE);

                            JSONArray dataArray = response.getJSONArray("data");
                            // 하나씩 꺼내서 메모리에 객체 생성하고,
                            // 여러개니까 어레이 리스트에 저장.
                            // 모든 데이터를 전부 저장하고 나면, 화면에 표시한다.
                            for(int i = 0 ; i < dataArray.length() ; i++) {
                                JSONObject data = dataArray.getJSONObject(i);
                                int id = data.getInt("id");
                                int userId = data.getInt("userId");
                                String title = data.getString("title");
                                String body = data.getString("body");

                                Posting posting = new Posting(id, userId, title, body);

                                postingArrayList.add(posting);
                            }
                            adapter = new PostingAdapter(MainActivity.this, postingArrayList);
                            recyclerView.setAdapter(adapter);

                        } catch (JSONException e) {
                            progressBar.setVisibility(View.GONE);

                            Toast.makeText(MainActivity.this,
                                    "파싱 에러",
                                    Toast.LENGTH_SHORT).show();
                            Log.i("ACTION MAIN", e.toString() );
                            return;
                        }

 


* adapter 만드는 포스팅

https://msdev-st.tistory.com/184

 

[Android Studio] Adapter.java 사용하기

Adapter 사용하기 Adapter 패키지 만들고, 안에 Adapter.java 파일을 만들기 1. 뷰 홀더 클래스를 만든다.- row.xml 파일과 이어주고, 변수 이름 저장하는 곳// 1. 뷰 홀더 클래스 만든다 public class ViewHolder e

msdev-st.tistory.com