package com.sound.prankparty.Utils;

import com.sound.prankparty.JSON.Category;
import com.sound.prankparty.JSON.SoundItem;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class JsonParser {

    public static List<Category> parseJson(String jsonString) {
        List<Category> categories = new ArrayList<>();

        try {
            //字符串转换为数组
            JSONArray jsonArray = new JSONArray(jsonString);
            //遍历数组里的每一个元素
            for (int i = 0; i < jsonArray.length(); i++) {
                //获取String字段的值
                JSONObject categoryObject = jsonArray.getJSONObject(i);
                String categoryId = categoryObject.getString("categoryId");
                String categoryName = categoryObject.getString("categoryName");
                String categoryUrl = categoryObject.getString("categoryUrl");

                JSONArray listArray = categoryObject.getJSONArray("list");
                List<SoundItem> soundItemList = new ArrayList<>();

                for (int j = 0; j < listArray.length(); j++) {
                    JSONObject soundObject = listArray.getJSONObject(j);
                    String mp3Url = soundObject.getString("mp3Url");
                    String preUrl = soundObject.getString("preUrl");
                    String title = soundObject.getString("title");
                    //创建ImageItem对象并添加到imageList中
                    soundItemList.add(new SoundItem(mp3Url, preUrl,title));
                }
                //创建Category对象并添加到categories列表中
                categories.add(new Category(categoryId,categoryName,categoryUrl, soundItemList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return categories;
    }

}
