简体   繁体   English

Android Studio 无法读取 JSONArray

[英]Android Studio having trouble reading a JSONArray

I'm a beginner to Android Studio and I'm just learning how to read in JSON files.我是 Android Studio 的初学者,我只是在学习如何阅读 JSON 文件。 I used logcat to find out that I'm getting an exception on the line declaraing the JSONArray dataList.我使用 logcat 发现我在声明 JSONArray dataList 的行上遇到异常。 My code is below for reference.我的代码如下供参考。

try{
            JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
            JSONArray dataList = jsonObject.getJSONArray("eateries");
            //Log.d("test", String.valueOf(dataList.length()));
            for(int i = 0; i < dataList.length(); i++){
                String EateryName = dataList.getJSONObject(i).getString("name");
                EateryList.add(EateryName);
            }
        }catch (JSONException e){
            e.printStackTrace();
            //Log.d("test", "exception");
        }

Follow these steps to solve your issue.请按照以下步骤解决您的问题。

  1. Check for asset folder/dir via code (file path must be accurate with.json).通过代码检查资产文件夹/目录(文件路径必须与.json 一致)。
  2. Check for file created/present in dir using File object (if not then create file).使用文件 object 检查目录中创建/存在的文件(如果没有,则创建文件)。
  3. Check for file size by reading the file using FileInputStream.通过使用 FileInputStream 读取文件来检查文件大小。
  4. If size > 0 then get data in byte-Array and convert byte-Array to string.如果 size > 0 则获取字节数组中的数据并将字节数组转换为字符串。
  5. Now, you have a string of json data.现在,您有一个 json 数据字符串。 Create JsonArray(your_string) and perform further operations you like.创建 JsonArray(your_string) 并执行您喜欢的进一步操作。
    Every step has a code available on this stack overflow.每个步骤都有一个可用于此堆栈溢出的代码。 Find and solve.找到并解决。
    Hope it helps.希望能帮助到你。

Check GrIsHu answer simply you have to do is create assests folder in root of project只需检查GrIsHu 的答案,您只需在项目的根目录中创建assests文件夹

在此处输入图像描述

Here is the original Link这是 原始链接

String myJsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "your.json");
Log.i("My data", jsonFileString);

Gson gson = new Gson();
Type listUserType = new TypeToken<List<User>>() { }.getType();

List<User> users_ = gson.fromJson(myJsonFileString, listUserType);
for (int i = 0; i < users.size(); i++) {
  Log.i("data", "> Item " + i + "\n" + users.get(i));
}

go through original post go通过原帖

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM