Android 读取assets目录下json数据

  • Post author:
  • Post category:其他


这是开源库 Android-PickerView中得工具类,感觉以后肯定会用得到就直接留一份,下次用就直接用


import android.content.Context;
import android.content.res.AssetManager;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * 读取 assets 目录下json文件工具类
 *
 * @author: 小嵩
 * @date: 2017/3/16 16:22
 */

public class GetJsonDataUtil {

    public String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public ArrayList<LocalAddressBean> getAddressData(Context context, String fileName, String key) {

        ArrayList<LocalAddressBean> list = new ArrayList<>();
        try {
            String json = getJson(context, fileName);
            JSONObject jsonObject = new JSONObject(json);
            JSONObject province = jsonObject.optJSONObject(key);
            if (province == null) return list;
            Iterator<String> keys = province.keys();
            while (keys.hasNext()) {
                String next = keys.next();
                String s = province.optString(next, "地址信息缺失");
                //保存 并并转化为本地数据类型
                list.add(new LocalAddressBean(next, s));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }
}

应用得话直接调用就行

        ArrayList<LocalAddressBean> addressData = new GetJsonDataUtil().getAddressData(MainActivity.this, "dddd.json", "86");
        LogUtils.e("TAG", addressData.toString());