본문 바로가기
Android

[Android/Java] JSON파싱(+ of type org.json.JSONArray cannot be converted to JSONObject 에러 )

by noddu 2022. 2. 1.
728x90
반응형

 

[
{
board_title: "title1",
board_date: "2020-02-02 00:00:00",
board_no: "1",
userEmail: "a",
board_content: "content1",
board_hit: "1"
},
{
board_title: "title2",
board_date: "2020-02-02 00:00:00",
board_no: "2",
userEmail: "b",
board_content: "content2",
board_hit: "1"
},
{
board_title: "title3",
board_date: "2020-02-02 00:00:00",
board_no: "3",
userEmail: "a",
board_content: "content3",
board_hit: "1"
}
]

 

board에 넣을 test용 JSON데이터 ( JSP )

 

 

 

 


 

@Override
public void onResponse(String response) {
    Log.d("News_response",response);

    try {

        JSONObject jsonObj = new JSONObject(response);
        JSONArray arrayArticles = jsonObj.getJSONArray("articles"); // articles라는 이름의 배열을 가져오기

        //response -> NewsData에 분류
        List<NewsData> news = new ArrayList<>();

        for(int i = 0, j = arrayArticles.length(); i < j; i++){
           JSONObject obj =  arrayArticles.getJSONObject(i);

            //Log.d("News",obj.toString());

            NewsData newsdata = new NewsData();
            newsdata.setTitle( obj.getString("title"));
            newsdata.setUrlToImage( obj.getString("urlToImage"));
            newsdata.setContent(obj.getString("description"));

            news.add(newsdata);
        }

배열의 이름이 있으면 다음과 같이 response를 JSONObject로 받아서

JSONArray로 그 이름의 배열을 가져와 데이터를 list에 넣을 수 있다

 

 

 

배열의 이름이 맨 위의 JSON 데이터처럼 없을때는 위와같이 사용하면

of type org.json.JSONArray cannot be converted to JSONObject  에러가 발생한다

 


 

@Override
public void onResponse(String response) {
    Log.d("board",response);

    try {
        JSONArray jsonArray = new JSONArray(response);

        //response -> BoardData 분류
        List<BoardData> boards = new ArrayList<>();

        for(int i = 0; i<jsonArray.length(); i++){
            JSONObject obj = jsonArray.getJSONObject(i);

            BoardData boardData = new BoardData();
            boardData.setBoard_no(obj.getString("board_no"));
            boardData.setBoard_subject(obj.getString("board_title"));
            boardData.setBoard_content(obj.getString("board_content"));
            boardData.setBoard_hit(obj.getString("board_hit"));
            boards.add(boardData);
        }

        adapter = new BoardAdapter(boards);

        recyclerView.setAdapter(adapter);

위와같이 response를 JSONArray로 받아서 그 길이만큼 list에 넣어주면 된다

반응형